Factories
Date: February 21st 2016
Last updated: February 21st 2016
A factory method is a design pattern that creates an instance of a class depending on 'some condition'. In the following example, I can switch between different classes using a look-up @staticmethod.
"""
Factory method example adapted from
https://gist.github.com/pazdera/1099559
"""
class Shape:
pattern = ""
# This is the factory method
@staticmethod
def get_shape(shape_pattern):
if (shape_pattern == "circle"):
return Circle()
elif (shape_pattern == "rectangle"):
return Rectangle()
else:
return None
class Circle(Shape):
pattern = "circle"
class Rectangle(Shape):
pattern = "rectangle"
# Testing (Run as main program)
if __name__ == "__main__":
circ = Shape.get_shape("circle")
print("%s(%s)" % (circ.pattern, circ.__class__.__name__))
rect = Shape.get_shape("rectangle")
print("%s(%s)" % (rect.pattern, rect.__class__.__name__))
Notice this example includes a @staticmethod decoration of get_shape(). Circle() and Rectangle() inherit from Shape so they both get the factory method too.
Shape
#<class 'factories.Shape'>
Shape.pattern
#''
Shape.get_shape
#<function Shape.get_shape at 0x7fa361298ea0>
Shape.get_shape()
#TypeError: get_shape() missing 1 required positional argument: 'shape_pattern'
Shape.get_shape('circle')
#<factories.Circle object at 0x7fa361211080>
circ = Shape.get_shape('circle')
circ
#<factories.Circle object at 0x7fa3612111d0>
circ.pattern
#'circle'
# As Circle(Shape) inherited from Shape(object) you can
# call get_shape('rectangle') and call a different shape class
circ.get_shape('rectangle')
#<factories.Rectangle object at 0x7fa361211080>
circ.get_shape('rectangle').pattern
#'rectangle'
#Although, I haven't figured out why you might want to have this circular pattern!
Useful resources: