Below is the code that implements a simple factory for a task that is very common. And even lower is the code that implements the factory method, the only difference is that the create_robot factory method in the first case returns an object directly, and in the second - through the factory, what is the extra layer of abstraction used for?
Simple factory `
import enum
from abc import ABC, abstractmethod
class RobotTypes(enum.Enum):
MAN = 1
WOMAN = 2
class Robot(ABC):
@abstractmethod
def greet(self):
pass
class RobotMan(Robot):
def greet(self):
print('Hello, i am Robot Man')
class RobotWoman(Robot):
def greet(self):
print('Hello, i am Robot Woman')
class RobotSystem:
@staticmethod
def create_robot(robot_type: RobotTypes) -> Robot:
match robot_type:
case RobotTypes.MAN:
return RobotMan()
case RobotTypes.WOMAN:
return RobotWoman()
if __name__ == '__main__':
system = RobotSystem()
robot_man = system.create_robot(RobotTypes.MAN)
robot_woman = system.create_robot(RobotTypes.WOMAN)
robot_man.greet()
robot_woman.greet()
`
Factory method `
import enum
from abc import ABC, abstractmethod
class RobotTypes(enum.Enum):
MAN = 1
WOMAN = 2
class Robot(ABC):
@abstractmethod
def greet(self):
pass
class RobotMan(Robot):
def greet(self):
print('Hello, i am Robot Man')
class RobotWoman(Robot):
def greet(self):
print('Hello, i am Robot Woman')
class RobotFactory(ABC):
@abstractmethod
def create_robot(self):
pass
class WomanRobotFactory(RobotFactory):
def create_robot(self):
return RobotWoman()
class ManRobotFactory(RobotFactory):
def create_robot(self):
return RobotMan()
class RobotSystem:
@staticmethod
def create_robot(factory: RobotFactory):
return factory.create_robot()
@staticmethod
def get_fabric(robot_type):
match robot_type:
case RobotTypes.MAN:
return ManRobotFactory()
case RobotTypes.WOMAN:
return WomanRobotFactory()
if __name__ == '__main__':
system = RobotSystem()
man_fabric = system.get_fabric(RobotTypes.MAN)
woman_fabric = system.get_fabric(RobotTypes.WOMAN)
man_robot = system.create_robot(man_fabric)
woman_robot = system.create_robot(woman_fabric)
man_robot.greet()
woman_robot.greet()
`
So what is the main difference between these two patterns?
Aucun commentaire:
Enregistrer un commentaire