方法一:
class FruitType:
""" 品种工厂类 """
def get_type(self, typ):
if typ == 0:
return Orange()
else:
return Grape()
class Orange:
""" 橘子实体类 """
def __init__(self):
self.name = "橘子"
def print_name(self):
print(f"水果:{self.name}")
class Grape:
""" 橘子实体类 """
def __init__(self):
self.name = "葡萄"
def print_name(self):
print(f"水果:{self.name}")
class FruitWeight:
""" 称重工厂类 """
def __init__(self, weight):
self.weight = float(weight)
def print_weight(self):
print(f"水果重量:{self.weight}")
class FruitPrice:
""" 价格工厂类 """
def get_price(self, typ, variety):
if typ == 0:
return OrangePrice(variety)
else:
return GrapePrice(variety)
class OrangePrice:
""" 橘子价格工厂类 """
def __init__(self, variety):
self.variety = variety
if self.variety == 1:
self.price = 0.8
elif self.variety == 2:
self.price = 1.2
else:
self.price = 1
def print_price(self):
print(f"橘子品种: {self.variety}, 价格: {self.price}")
class GrapePrice:
""" 葡萄价格工厂类 """
def __init__(self, variety):
self.variety = variety
if self.variety == 1:
self.price = 1.5
elif self.variety == 2:
self.price = 1.2
else:
self.price = 2
def print_price(self):
print(f"葡萄品种: {self.variety}, 价格: {self.price}")
class FruitFactory:
""" 任务分配(分配具体实例化的类) """
def __init__(self, typ, weight, variety):
self.fruit = FruitType().get_type(typ)
self.weight = FruitWeight(weight)
self.price = FruitPrice().get_price(typ, variety)
def amount_price(self):
print(f"合计金额: {self.price.price * self.weight.weight}")
class Consumer:
""" 消费者类 """
def __init__(self, typ, weight, variety):
self.typ = typ
self.weight = weight
self.variety = variety
def request(self):
return self.typ, self.weight, self.variety
if __name__ == '__main__':
"""
type: 1 橘子
type: 2 葡萄
variety: 品种
"""
consumer = Consumer(1, 3, 2) # 实例化消费者
fruit_factory = FruitFactory(*consumer.request())
fruit_factory.amount_price()
方法二:
from abc import ABCMeta, abstractmethod
class Creator(metaclass=ABCMeta):
@abstractmethod
def factory_a(self):
pass
@abstractmethod
def factory_b(self):
pass
@classmethod
def get_creator(self, typ):
if typ == 1:
return ConcreteCreatorA()
else:
return ConcreteCreatorB()
class ConcreteCreatorA(Creator):
def factory_a(self):
return ProductA1()
def factory_b(self):
return ProductA2()
class ConcreteCreatorB(Creator):
def factory_a(self):
return ProductB1
def factory_b(self):
return ProductB2
class ProductA1:
def __init__(self):
print("ProductA1……")
class ProductB1:
def __init__(self):
print("ProductB1……")
class ProductA2:
def __init__(self):
print("ProductA2……")
class ProductB2:
def __init__(self):
print("ProductB2……")
if __name__ == '__main__':
Creator.get_creator(1).factory_a()