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

36 lines
677 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 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()