`
rockkyle
  • 浏览: 10386 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

单例模式 python

 
阅读更多

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界 访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

一、装饰器实现

def sing(cls):
        instance={}
        def _sing(*args,**kwargs):
                if cls not in instance:
                        instance[cls]=cls(*args,**kwargs)
                return instance[cls]
        return _sing

@sing
class myclass(object):
        a=1
        def __init__(self,x,y):
                self.x=x
                self.y=y
a1=myclass(1,2)
a2=myclass()
print id(a1),id(a2)

 结果:

140576008975184 140576008975184

 PS:id方法的返回值就是对象的内存地址

二、魔法方法__new__实现

 

 代码:

class single(object):
#创建对象,返回当前对象的实例
        def __new__(cls):
                return cls
class test(single):
        pass
one=test()
two=test()
print id(one),id(two)

 结果:

18830960 18830960

 运行的时候,其中__new__中参数cls为test,

 或者将类的实例绑定在变量上

class single1(object):
        def __new__(cls):
                if not hasattr(cls,'ins'):
# 获取cls对象,并将ins属性绑定cls对象
                        orig=super(single1,cls)
                        cls.ins=orig.__new__(cls)
                return cls.ins
class test1(single1):
        pass
on=test1()

tw=test1()
print id(on),id(tw)

 结果:

140541601328976 140541601328976

 三、元类实现

 

class A(type):
#       def __init__(cls,name,bases,dict):
#               super(A,cls).__init__(name,bases,dict)
#               cls._instance=None
#当把一个实例当作方法来调用的时候当把一个实例当作方法来调用的时候,调用__call__
#a=A(),a()写法会调用__call__
        def __call__(cls):
                return cls
class B(object):
        __metaclass__=A

one=B()
two=B()
print id(one),id(two)

 结果:

32129184 32129184

 

分享到:
评论
Global site tag (gtag.js) - Google Analytics