class ComputerFactory:
_obj = None
_init_flag = True
def create_computer(self,brand):
if brand == '联想':
return Lenovo()
elif brand == '华硕':
return Asus()
elif brand == '神舟':
return Hasee()
else:
return '未知品牌,无法创建'
def __new__(cls, *args, **kwargs):
if cls._obj == None:
cls._obj = object.__new__(cls)
return cls._obj
def __init__(self):
if ComputerFactory._init_flag:
print("init ComputerFactory....")
ComputerFactory._init_flag = False
class Computer(ComputerFactory):
def __init__(self,unit,amount):
self.unit = unit
self.amount = amount
def calculate(self):
print('总销售额是:{0}'.format(self.unit*self.amount))
class Lenovo(Computer):
def __init__(self,unit,amount,year):
self.year = year
Computer.__init__(self,unit,amount)
def calculate(self):
print('第{0}年的总销售额是{1}'.format(self.year,self.unit*self.amount))
class Asus(Computer):
def __init__(self, unit, amount, year):
self.year = year
Computer.__init__(self, unit, amount)
def calculate(self):
print('第{0}年的总销售额是{1}'.format(self.year, self.unit * self.amount))
class Hasee(Computer):
def __init__(self, unit, amount, year):
self.year = year
Computer.__init__(self, unit, amount)
def calculate(self):
print('第{0}年的总销售额是{1}'.format(self.year, self.unit * self.amount))
factory = ComputerFactory()
c1 = factory.create_computer('联想')
c2 = factory.create_computer('华硕')
c3 = factory.create_computer('神舟')
print(c1)
print(c2)
print(c3)
l=Lenovo()
l.calculate('联想',3000,4789,2020)
老师好,最后想分别计算各个品牌的数据并打印输出,这里的代码不会写。