一、单例模式
-
利用__new__设置只创建一个对象,利用__init__中初始化一次
class PersonTest(object): __onlyOne = None __isFirst = True def __new__(cls, id, name): if not PersonTest.__onlyOne: PersonTest.__onlyOne = object.__new__(cls) return PersonTest.__onlyOne def __init__(self, id, name): if PersonTest.__isFirst: self.id = id self.name = name PersonTest.__isFirst = False pt1 = PersonTest('001','tom') pt2 = PersonTest('99','rose') print(id(pt1), id(pt2)) # 2660597279264 2660597279264 print(pt1.id, pt2.id) # 001 001 ;当不在init中设置时,为 99 99
二、工厂模式
class Mobile(object):
def __init__(self,price):
self.price = price
class Iphone(Mobile):
def __init__(self, price,level):
super(Iphone, self).__init__(price)
self.brand = 'Apple'
self.level = level
print(self.level,'正在生产')
class Sasung(Mobile):
def __init__(self, price, level,pencil):
super(Sasung, self).__init__(price)
self.brand = 'Sasung'
self.level = level
self.pencil = pencil
print(self.level,'正在生产')
#构建工厂
class Factory(object):
def __init__(self):
self.name = '富士康'
def setorder(self, brand, price,level,number):
mbs = []
for i in range(number):
iphone = Iphone(price,level)
mbs.append(iphone)
return mbs
class FactoryIphone(Factory):
pass
class FactorySasung(Factory):
pass
#构件专卖店
class Shop(object):
def __init__(self, id, brand, address):
self.id = id
self.brand = brand
self.address = address
def order(self, number):
pass
def sale(self, num):
pass
class ShopIphone(Shop):
score = 0
def __init__(self, id, brand, address):
super(ShopIphone, self).__init__(id, brand, address)
def order(self, number):
fc = Factory()
mbs = fc.setorder('Apple',8000,'xr',number)
ShopIphone.score += len(mbs)
def sale(self, num):
ShopIphone.score -= num
class ShopSasung(Shop):
pass
shop01 = ShopIphone('001','Apple','独墅湖')
shop02=ShopIphone('002','Apple','金鸡湖')
shop01.order(10)
shop02.order(30)
shop02.sale(132)
print(shop01.score)
来源:https://blog.csdn.net/qq_38328762/article/details/99072769