tuoheng_algN/test/设计模式/简单工厂模式/demo1.py

44 lines
777 B
Python

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 AbcFruitFactory(ABC):
@abstractmethod
def create_fruit(self):
pass
class AppleFactory(AbcFruitFactory):
def create_fruit(self):
return Apple('苹果')
class OrangeFactory(AbcFruitFactory):
def create_fruit(self):
return Grape('葡萄')
fruit1 = AppleFactory().create_fruit()
fruit1.make_juice() # 制作苹果汁
fruit2 = OrangeFactory().create_fruit()
fruit2.make_juice()