from abc import ABC, abstractmethod
class Fruit(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def make_juice(self):
pass
class Apple(Fruit):
def make_juice(self):
print(f"制作{self.name}汁")
class Grape(Fruit):
def make_juice(self):
print(f"制作{self.name}酒")
class FruitFactory():
@classmethod
def create_fruit(cls, name):
if name == 'apple':
return Apple('苹果')
elif name == 'grape':
return Grape("葡萄")
fruit1 = FruitFactory.create_fruit('apple')
fruit1.make_juice()
fruit2 = FruitFactory.create_fruit('grape')
fruit2.make_juice()
制作苹果汁 制作葡萄酒
1.FruitFactory
就是工厂角色,专门负责生产产品。
2.Fruit
是抽象产品角色,代码里不会创建它的实例对象。
3.Apple
和 Grape
是具体产品角色, Fruit
是他们的父类,
具体产品角色必须实现 make_juice
方法。
现在,来思考一个问题,当新增一种水果种类时,代码需要做哪些改动呢?就以 Orange
为例,
必须新增一个 Orange
类,这个类继承 Fruit
类,
接下来,需要修改 FruitFactory
的 create_fruit
方法,
当 name
为的值是 orange
时返回 Orange
的示例对象。
简单工厂模式的优点在于降低开发人员对实例对象创建的理解成本, 值需要向接口里传入特定的实参就可以获得自己想要的实例对象。
简单工厂模式的缺点也十分明显,当具体产品角色非常多时,维护工厂角色就会变得繁琐困难, 因此简单工厂模式更适合具体产品角色较少的场景。