I have been reading today about the Abstract Factory Pattern, and tried to make the following implementation.
I have seen a lot of implementations in the internet, where they use
switch statements, but I must say that I didn't like that much, since the more factories you make, it seems to me that it makes very difficult to add new products, if needed.
Anyways, I was hoping you to take a look at it and let me know your opinions. Thanks in advance for taking your time to review it.
from abc import ABC, abstractmethod class PlayerFactory(ABC): """ This class is meant to be an interface """ @abstractmethod def create_goalkeeper(self): pass @abstractmethod def create_defender(self): pass class FootballPlayerFactory(PlayerFactory): def create_goalkeeper(self): return FootballGoalkeeper() def create_defender(self): return FootballDefender() class HockeyPlayerFactory(PlayerFactory): def create_goalkeeper(self): return HockeyGoalkeeper() def create_defender(self): return HockeyDefender()
class FootballPlayer: def __init__(self, uses_hands): self.uses_hands = uses_hands def play(self): print("I'm playing football!") class FootballGoalkeeper(FootballPlayer): def __init__(self): super(FootballGoalkeeper, self).__init__(uses_hands=True) class FootballDefender(FootballPlayer): def __init__(self): super(FootballDefender, self).__init__(uses_hands=False)
Hockey players (my creativity stopped here, so I didn't include any difference between goalkeepers and defenders)
class HockeyPlayer: def play(self): print("I'm playing hockey!") class HockeyGoalkeeper(HockeyPlayer): pass class HockeyDefender(HockeyPlayer): pass