Python设计模式之单例模式实例
注:使用的是python 2.7。
一个简单实现
class foo(object):
__instance = none
def __init__(self):
pass
@classmethod
def getinstance(cls):
if(cls.__instance == none):
cls.__instance = foo()
return cls.__instance
if __name__ == '__main__':
foo1 = foo.getinstance()
foo2 = foo.getinstance()
print id(foo1)
print id(foo2)
print id(foo())
输出的前两个结果是相同的(id(foo1)与id(foo2)的值相同),第三个结果和前两个不同。这里类方法getinstance()用于获取单例,但是类本身也可以实例化,这样的方式其实并不符合单例模式的要求。但是这样做也有好处,代码简单,大家约定好这样子调用就行了。但是最好在类的命名上也体现了出来这是一个单例类,例如foo_singleton。
换一个思路
先说一下init和new的区别:
class foo(object):
__instance = none
def __init__(self):
print 'init'
if __name__ == '__main__':
foo = foo()
运行结果是:
init
而下面的示例:
class foo(object):
__instance = none
def __init__(self):
print 'init'
def __new__(cls, *args, **kwargs):
print 'new'
if __name__ == '__main__':
foo = foo()
运行结果是:
new是一个类方法,会创建对象时调用。而init方法是在创建完对象后调用,对当前对象的实例做一些一些初始化,无返回值。如果重写了new而在new里面没有调用init或者没有返回实例,那么init将不起作用。以下内容引用自http://docs.python.org/2/reference/datamodel.html#object.new
if __new__() returns an instance of cls, then the new instance's __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
if __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.
这样做:
class foo(object):
__instance = none
def __init__(self):
print 'init'
def __new__(cls, *args, **kwargs):
print 'new'
if cls.__instance == none:
cls.__instance = cls.__new__(cls, *args, **kwargs)
return cls.__instance
if __name__ == '__main__':
foo = foo()
错误如下:
runtimeerror: maximum recursion depth exceeded in cmp
而这样也有一样的错误:
class foo(object):
__instance = none
def __init__(self):
if self.__class__.__instance == none:
self.__class__.__instance = foo()
print 'init'
if __name__ == '__main__':
foo = foo()
该怎么做呢?
下面参考了http://*.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python/31887#31887:
class foo(object):
__instance = none
def __new__(cls, *args, **kwargs):
print 'hhhhhhhhh'
if not cls.__instance:
cls.__instance = super(foo, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def hi(self):
print 'hi, world'
print 'hi, letian'
if __name__ == '__main__':
foo1 = foo()
foo2 = foo()
print id(foo1)
print id(foo2)
print isinstance(foo1, object)
print isinstance(foo1, foo)
foo1.hi()
运行结果:
hhhhhhhhh
hhhhhhhhh
39578896
39578896
true
true
hi, world
hi, letian
那么,到底发生了什么,我们先回顾一下super:
>>> print super.__doc__
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
typical use to call a cooperative superclass method:
class c(b):
def meth(self, arg):
super(c, self).meth(arg)
可以肯定上面的单例模式代码中的这一行代码:
cls.__instance = super(foo, cls).__new__(cls, *args, **kwargs)
super(foo, cls)是object,super(foo, cls).new方法使用的是object的new方法。我们看一下object.new方法的作用:
>>> print object.__new__.__doc__
t.__new__(s, ...) -> a new object with type s, a subtype of t
如果是一个继承链
class fo(object):
def __new__(cls, *args, **kwargs):
print 'hi, i am fo'
return super(fo, cls).__new__(cls, *args, **kwargs)
class foo(fo):
__instance = none
def __new__(cls, *args, **kwargs):
if not cls.__instance:
print foo is cls
print issubclass(cls, fo)
print issubclass(cls, object)
cls.__instance = super(foo, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def hi(self):
print 'hi, world'
if __name__ == '__main__':
foo1 = foo()
foo1.hi()
print isinstance(foo1, foo)
print isinstance(foo1, fo)
print isinstance(foo1, object)
运行结果如下:
true
true
true
hi, i am fo
hi, world
true
true
true
如果如下定义fo,也正常运行:
class fo(object):
pass
但是,若这样定义:
class fo(object):
def __new__(cls, *args, **kwargs):
print 'hi, i am fo'
运行时报错如下:
attributeerror: 'nonetype' object has no attribute 'hi'
上一篇: python中的实例方法、静态方法、类方法、类变量和实例变量浅析
下一篇: 这么小的床,我媳妇睡哪?