专业版:
https://blog.csdn.net/qq_27825451/article/details/84284681
非专业版:
想要看懂这篇文章,得先看上一篇,因为用的比喻是类似的
第一篇:https://blog.csdn.net/wangsais54977/article/details/105573894
第二篇:https://blog.csdn.net/wangsais54977/article/details/105578386
简单工厂模式是一个小工厂,工厂方法模式是一个园区,抽象工厂模式是一个区,如某城市的高新区,在这个高新区中有很多园区,其中有软件园,工业园等等,高新区作为最高级别的工厂类,我们把它叫做超级工厂,我们把其中的园区叫做普通工厂。
直接看代码吧!
第一步,先写了一个软件园类,然后里面的软件公司都继承它。
# 先看软件园
class SoftwareCompany:
def develop_software(self):
pass
# 开发游戏的公司
class Game(SoftwareCompany):
def develop_software(self):
print('开发游戏')
# 开发社交软件的公司
class SocialSoftware(SoftwareCompany):
def develop_software(self):
print('开发社交软件')
第二步,再写一个工业园类,然后里面的工厂都继承它。
# 工业园
class IndustryCompany:
def create_product(self):
pass
# numerical control 数控机床
class NumericalControl(IndustryCompany):
def create_product(self):
print('制作数控机床')
# Mobile phone 手机
class MobilePhone(IndustryCompany):
def create_product(self):
print("制作手机")
第三步,写出软件园类和工业园类的工厂类,这里和简单工厂类很相似
# 写出软件园类和工业园类的工厂类
class IFactory:
def create(self, name):
pass
# 软件园工厂类
class SoftwareFactory(IFactory):
def create(self, name):
if name == 'Game' :
return Game()
elif name == 'SocialSoftware':
return SocialSoftware()
else:
return None
# 工业园工厂类
class IndustryCompany(IFactory):
def create(self, name):
if name == 'NumericalControl':
return NumericalControl()
elif name == 'MobilePhone':
return MobilePhone()
else:
return None
第四步,在将软件园工厂类和工业园工厂类整合在一起,形成一个超级工厂
# 高新区/超级工厂
class SuperFactory:
def get_factory(self, name):
if name == 'SoftwareFactory':
return SoftwareFactory()
elif name == 'IndustryCompany':
return IndustryCompany()
else:
return None
查看效果
if __name__ == '__main__':
Game = SuperFactory().get_factory('SoftwareFactory').create('Game').develop_software()
SocialSoftware = SuperFactory().get_factory('SoftwareFactory').create('SocialSoftware').develop_software()
NumericalControl = SuperFactory().get_factory('IndustryCompany').create('NumericalControl').create_product()
MobilePhone = SuperFactory().get_factory('IndustryCompany').create('MobilePhone').create_product()
结果:
开发游戏
开发社交软件
制作数控机床
制作手机
说实话,这还是很复杂的,抽象的层数较高,看看就好了。