使用工厂模式、单例模式实现如下需求:
(1) 电脑工厂类 ComputerFactory 用于生产电脑 Computer。工厂类使用单例模式,也就是说只能有一个工厂对象。
(2) 工厂类中可以生产各种品牌的电脑:联想、华硕、神舟
(3) 各种品牌的电脑使用继承实现:
(4) 父类是 Computer 类,定义了 calculate 方法
(5) 各品牌电脑类需要重写父类的 calculate
继承
class ComputerFactory:
def __init__(self, lenovo, ASUS, HASSEE):
self.lenovo = lenovo
self.ASUS = ASUS
self.HASSEE = HASSEE
def createComputer(self):
print(f"创建了电脑")
def calculate(self):
print("我是父")
class lenovo(ComputerFactory): # 联想
def calcula(self):
print("我是继承的lenovo过来的")
class ASUS(ComputerFactory): # 华硕
def calcula(self):
print("我是继承的ASUS过来的")
class HASSEE(ComputerFactory): # 神舟
def calcula(self):
print("我是继承的HASSEE过来的")
if __name__ == '__main__':
Computer = ComputerFactory(lenovo, ASUS, HASSEE)
Computer.lenovo.calcula(1)
组合
# class ComputerFactory:
# def __init__(self, lenovo, ASUS, HASSEE):
# self.lenovo = lenovo
# self.ASUS = ASUS
# self.HASSEE = HASSEE
#
# def createComputer(self):
# print(f"创建了电脑")
#
# def calculate(self):
# pass
#
#
# class lenovo(): # 联想
# def calcula(self):
# print("我是继承的lenovo过来的")
#
#
# class ASUS(): # 华硕
# def calcula(self):
# print("我是继承的ASUS过来的")
#
#
# class HASSEE(): # 神舟
# def calcula(self):
# print("我是继承的HASSEE过来的")
#
#
# c = lenovo()
# a = ASUS()
# b = HASSEE()
# Computer = ComputerFactory(c, a, b)
# Computer.lenovo.calcula()