Home  >  Article  >  Backend Development  >  Python下singleton模式的实现方法

Python下singleton模式的实现方法

WBOY
WBOYOriginal
2016-06-16 08:43:101086browse

很多开发人员在刚开始学Python 时,都考虑过像 c++ 那样来实现 singleton 模式,但后来会发现 c++ 是 c++,Python 是 Python,不能简单的进行模仿。

Python 中常见的方法是借助 global 变量,或者 class 变量来实现单件。本文就介绍以decorator来实现 singleton 模式的方法。示例代码如下:

##----------------------- code begin -----------------------

# -*- coding: utf-8 -*-
def singleton(cls):
"""Define a class with a singleton instance."""
instances = {}
def getinstance(*args, **kwds):
return instances.setdefault(cls, cls(*args, **kwds))
return getinstance
 
##1 未来版Python支持Class Decorator时可以这样用
class Foo(object):
def __init__(self, attr=1):
self.attr = attr

Foo = singleton( Foo ) ##2 2.5及之前版不支持Class Decorator时可以这样用

if __name__ == "__main__":
ins1 = Foo(2) # 等效于: ins1 = singleton(Foo)(2)
print "Foo(2) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins1), ins1.attr, ('error', 'ok')[ins1.attr == 2])
ins2 = Foo(3)
print "Foo(3) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins2), ins2.attr, ('error', 'ok')[ins2.attr == 2])
ins2.attr = 5
print "ins.attr=5 -> ins.attr=%d, %s" % (ins2.attr, ('error', 'ok')[ins2.attr == 5])
 
##------------------------ code end ------------------------

输出:

Foo(2) -> id(ins)=19295376, ins.attr=2, ok
Foo(3) -> id(ins)=19295376, ins.attr=2, ok
ins.attr=5 -> ins.attr=5, ok
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn