Skip to content

Factory

Factory Methods are typically static methods in a class that return an instance of that class. This is helpful when it's not obvious how to construct an item, but still want it to be created wholesale and not piecewise like builders. A Factory is a separate class with factory methods dedicated to creating another type.

python
from enum import Enum
from math import *

class CoordinateSystem(Enum):
    CARTESIAN = 1
    POLAR = 2

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f'x: {self.x}, y: {self.y}'

    # Bad way, requires more steps
    # def __init__(self, a, b, system=CoordinateSystem.CARTESIAN):
    #     if system == CoordinateSystem.CARTESIAN:
    #         self.x = a
    #         self.y = b
    #     elif system == CoordinateSystem.POLAR:
    #         self.x = a * sin(b)
    #         self.y = a * cos(b)    
    #     # steps to add a new system
    #     # 1. augment CoordinateSystem
    #     # 2. change init method

    @staticmethod
    def new_cartesian_point(x, y):
        return Point(x, y)

    @staticmethod
    def new_polar_point(rho, theta):
        return Point(rho * sin(theta), rho * cos(theta))

    # Can have factory within or ourside of class
    class Factory:
        @staticmethod
        def new_cartesian_point(x, y):
            return Point(x, y)

    factory = Factory()

# take out factory methods to a separate class
class PointFactory:
    @staticmethod
    def new_cartesian_point(x, y):
        return Point(x, y)

    @staticmethod
    def new_polar_point(rho, theta):
        return Point(rho * sin(theta), rho * cos(theta))