1. 工厂模式(Factory Pattern)
想象一下,你有个大冰箱,每次需要冰淇淋时,你都不用直接打开冷冻室,而是通过一个工厂方法来决定要哪种口味。
def create_creamy_icecream(): return CreamyIceCream()
def create_fruit_icecream(): return FruitIceCream()
class IceCreamFactory:
@staticmethod
def get_icecream(kind):
if kind == 'creamy':
return create_creamy_icecream()
elif kind == 'fruit':
return create_fruit_icecream()
2. 装饰器模式(Decorator Pattern)
好比给房间添加装饰,改变外观但不改变核心功能。比如,给打印语句加上颜色:
def color_decorator(func):
def wrapper(color):
print(f"{color} {func(color)}")
return wrapper
@color_decorator
de