一、定义两个需要实例化的系列
class Kouzhao:
def houdu(self):
pass
class N95(Kouzhao):
def houdu(self):
print('3 层 ....')
class Yihu(Kouzhao):
def houdu(self):
print('3 层')
class Putong(Kouzhao):
def houdu(self):
print('2 层 ....')
class Job:
def get_name(self):
pass
class Doctor(Job):
def get_name(self):
print('doctor')
class Student(Job):
def get_name(self):
print('student')
二、简单工厂模式
根据传入的参数返回相应的实例对象,一个工厂类来负责所有产品的创建,集中生产
def choose_kouzhao(type):
if type == 'n95':
return N95()
elif type == 'yihu':
return Yihu()
elif type == 'putong':
return Putong
三、方法工厂模式
一个工厂只负责创建一个产品遵从了单一职责原则,分散生产
class Method_Factory:
def get_kouzhao(self):
pass
class N95_factory(Method_Factory):
def get_kouzhao(self):
return N95()
class Yihu_factory(Method_Factory):
def get_kouzhao(self):
return Yihu()
class Putong_factory(Method_Factory):
def get_kouzhao(self):
return Putong()
def factory_choose(type):
if type == 'n95':
return N95_factory()
elif type == 'yihu':
return Yihu_factory()
elif type == 'putong':
return Putong_factory()
四、抽象工厂模式
当方法工厂模式中,工厂类太多时,对于同一系列的集中式生产,对于不同系列的分散式生产,面向多个产品系列
class Kouzhao_factory:
# def create_kouzhao(self):
# pass
def get_n95(self):
return N95()
def get_putong(self):
return Putong()
def get_yihu(self):
return Yihu()
class Job_factory:
def create_job(self, type):
if type == 'd':
return Doctor()
if type == 's':
return Student()
def get_factory(name):
if name == 'job':
return Job_factory()
if name == 'kouzhao':
return Kouzhao_factory()
来源:CSDN
作者:浪子哥学习笔记
链接:https://blog.csdn.net/qq_36072270/article/details/104517355