← back

Factory Method (Creational Pattern)

Written by Matthias Osswald - January 2021
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.

from abc import ABC
from abc import abstractmethod

class AnimalCreator(ABC):
    def make_animal(self):

    def get_sentence(self) -> str:
        animal = self.make_animal()
        return animal.get_sound()

class AnimalProduct(ABC):
    def get_sound(self) -> str:

class FishCreator(AnimalCreator):
    def make_animal(self) -> AnimalProduct:
        return ConcreteFish()

class HumanCreator(AnimalCreator):
    def make_animal(self) -> AnimalProduct:
        return ConcreteHuman()

class ConcreteFish(AnimalProduct):
    def get_sound(self) -> str:
        return "Blub blub!"

class ConcreteHuman(AnimalProduct):
    def get_sound(self) -> str:
        return "Hello World!"

def client_code(creator: AnimalCreator) -> None:

if __name__ == "__main__":