← back

Builder (Creational Pattern)

Written by Matthias Osswald - December 2020
This blog series about design patterns is a reference, how patterns described in "Design Patterns: Elements of Reusable Object-Oriented Software" by E. Gamma et al. can be implemented in Python.

If you prefere, there are some more interfaceish things like e.g. zope.interface to use instead of ABC (which is closer to an abstract class than an interface).

from abc import ABC
from abc import abstractmethod

class IUfoBuilder(ABC):
    def get_origin() -> str:
        """Get the UFOs origin

    def get_shape() -> str:
        """Get the UFOs shape

class Ufo:
    def __init__(self):
        self.__origin = None
        self.__shape = None

    def set_origin(self, origin):
        self.__origin = origin

    def set_shape(self, shape):
        self.__shape = shape

    def __str__(self):
        return f"UFO from {self.__origin}, {self.__shape} shaped."

class MagratheaUfoBuilder(IUfoBuilder):
    def get_origin():
        return "Magrathea"

    def get_shape():
        return "saucer"

class AlphaCentauriUfoBuilder(IUfoBuilder):
    def get_origin():
        return "Alpha Centauri"

    def get_shape():
        return "mug"

class UfoDirector:
    __builder = None

    def set_builder(self, builder):
        self.__builder = builder

    def construct(self):
        ufo = Ufo()
        origin = self.__builder.get_origin()
        shape = self.__builder.get_shape()
        return ufo

if __name__ == '__main__':
    ufo_director = UfoDirector()

    magrathea_ufo_builder = MagratheaUfoBuilder()
    alpha_centauri_ufo_builder = AlphaCentauriUfoBuilder()

    magrathea_ufo = ufo_director.construct()

    alpha_centauri_ufo = ufo_director.construct()