设计模式-抽象工厂模式
内容:定义一个工厂类接口,让工厂子类来创建一系列相关或者相互依赖的对象
例如:生产一部手机你,需要手机壳、CPU、操作系统三类对象来进行组装,其中每类对象都有不同的种类。对每个具体工厂,分别生产一部手机需要的三个对象
相比工厂方法模式,抽象工厂模式的每个具体工厂都生产一套产品
from abc import ABCMeta, abstractclassmethod
# 定义三个接口
class Cpu(metaclass=ABCMeta):
@abstractclassmethod
def show_cpu(self):
pass
class Os(metaclass=ABCMeta):
@abstractclassmethod
def show_os(self):
pass
class PhoneCase(metaclass=ABCMeta):
@abstractclassmethod
def show_phonecase(self):
pass
class XiaoLongCpu(Cpu):
def show_cpu(self):
print('骁龙cpu')
class InterCpu(Cpu):
def show_cpu(self):
print('英特尔cpu')
class AndroidOs(Os):
def show_os(self):
print("安卓系统")
class IosOs(Os):
def show_os(self):
print("苹果系统")
class BigPhoneCase(PhoneCase):
def show_phonecase(self):
print("大手机壳")
class MidPhoneCase(PhoneCase):
def show_phonecase(self):
print("中等机壳")
class SmallPhoneCase(PhoneCase):
def show_phonecase(self):
print("小型手机壳")
# 定义一个接口,手机工厂,初步定义手机需要的对象
class PhoneFactory(metaclass=ABCMeta):
@abstractclassmethod
def make_os(self):
pass
@abstractclassmethod
def make_cpu(self):
pass
@abstractclassmethod
def make_phonecase(self):
pass
class HuaweiPhoneFactory(PhoneFactory):
def make_os(self):
return AndroidOs()
def make_cpu(self):
return XiaoLongCpu()
def make_phonecase(self):
return BigPhoneCase()
class IPhoneFactory(PhoneFactory):
def make_os(self):
return IosOs()
def make_cpu(self):
return InterCpu()
def make_phonecase(self):
return SmallPhoneCase()
class Phone():
def __init__(self, cpu, os, phonecase):
self.cpu = cpu
self.os = os
self.phonecase = phonecase
def show_info(self):
self.cpu.show_cpu()
self.os.show_os()
self.phonecase.show_phonecase()
def make_phone(factory):
cpu = factory().make_cpu()
os = factory().make_os()
phonecase = factory().make_phonecase()
return Phone(cpu, os, phonecase)
make_phone(HuaweiPhoneFactory).show_info()
make_phone(IPhoneFactory).show_info()
角色
抽象工厂角色 PhoneFactory
具体工厂角色 HuaweiPhoneFactory IPhoneFactory
抽奖产品角色 Cpu Os PhoneCase
具体产品角色 AndroidOs IosOs
客户端