单例---类方法方式
class Single():
def __init__(self,name):
self.name = name
@classmethod
def instance(cls,*args,**kwargs):
if not hasattr(Single,"_instance"):
Single._instance = Single(*args,**kwargs)
return Single._instance
s1 = Single.instance('Gage')
s2 = Single.instance()
print(s1)
print(s2)
单例---new方式
class Single(object):
__isstance = None
__first_init = False
def __new__(cls,**kwargs):
if not cls.__isstance:
cls.__isstance = object.__new__(cls)
return cls.__isstance
def __init__(self,name):
if not self.__first_init:
self.name = name
Singleton.__first_init = True
a = Single('a')
b = Single('b')
print(id(a))
print(id(b))
工厂模式
# 首先定义一个抽象基类
class CarStore(object):
# 定义生产汽车的方法
def createcar(self,name):
pass
# 根据类型去生产车
def order(self,name):
self.car = self.createcar(name)
self.car.move()
# 定义4s店 实现抽象类
class AoDiCarStore(CarStore):
def createcar(self,name):
self.factory = CarFactory()
return self.factory.createcar(name)
# 创建一个车
class AoDi():
def move(self):
print('移动')
# 定义一个工厂
class CarFactory():
def createcar(self,name):
self.name = name
if self.name == 'AoDi':
self.car = AoDi()
return self.car
aodi = AoDiCarStore()
aodi.order('AoDi')
本文首发于python黑洞网,博客园同步更新