python设计模式之单例模式

单例模式
通过Singleton模式,全局保证只有一个实例,在python中怎么用呢?

python的例子
我这里实现了一个pymongo连接的‘缓存’,为了保证在一个进程里面调用只产生一个连接数

Python
class ConnectionSingleton(object): '''通过重载实例化函数__new__缓存mongodb连接''' conn=None def __new__(cls,*args,**kwds): if cls.conn is None: cls.conn=pymongo.MongoClient() return cls.conn
1
2
3
4
5
6
7
8
class ConnectionSingleton ( object ) :
     '''通过重载实例化函数__new__缓存mongodb连接'''
     conn = None
     def __new__ ( cls , * args , * * kwds ) :
         if cls . conn is None :
             cls . conn = pymongo . MongoClient ( )
         return cls . conn
 

调用的时候可以

Python
db = ConnectionSingleton()
1
2
db = ConnectionSingleton ( )
 

和pymongo相关的温馨提示
请不要使用pymongo.Connection,官网不推荐,并且有个问题,当你close它的实例,连接数并没有立刻减少
做好数据库操作的类变量的封装,调用完毕要显式close/disconnect

Simplest way to use singleton pattern in Python it's move all code to separate module and import it:

singleton.py:

Python
from pymongo import MongoClient client = MongoClient("localhost", 27017) db = client.newsdb news = db.news
1
2
3
4
5
     from pymongo import MongoClient
     client = MongoClient ( "localhost" , 27017 )
     db = client . newsdb
     news = db . news
 

and use it in other modules:

Python
import singleton print(singleton.news)
1
2
3
import singleton
print ( singleton . news )
 

单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。

在 Python 中,我们可以用多种方法来实现单例模式:

  • 使用模块
  • 使用 __new__
  • 使用装饰器(decorator)
  • 使用元类(metaclass)

使用模块

其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:

Python
# mysingleton.py class My_Singleton(object): def foo(self): pass my_singleton = My_Singleton()
1
2
3
4
5
6
7
# mysingleton.py
class My_Singleton ( object ) :
     def foo ( self ) :
         pass
 
my_singleton = My_Singleton ( )
 

将上面的代码保存在文件 mysingleton.py 中,然后这样使用:

Python
from mysingleton import my_singleton my_singleton.foo()
1
2
3
4
from mysingleton import my_singleton
 
my_singleton . foo ( )
 

使用 __new__

为了使类只能出现一个实例,我们可以使用 __new__ 来控制实例的创建过程,代码如下:

Python
class Singleton(object): _instance = None def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a = 1
1
2
3
4
5
6
7
8
9
10
class Singleton ( object ) :
     _instance = None
     def __new__ ( cls , * args , * * kw ) :
         if not cls . _instance :
             cls . _instance = super ( Singleton , cls ) . __new__ ( cls , * args , * * kw )   
         return cls . _instance  
 
class MyClass ( Singleton ) :   
     a = 1
 

在上面的代码中,我们将类的实例和一个类变量 _instance 关联起来,如果 cls._instance 为 None 则创建实例,否则直接返回 cls._instance

执行情况如下:

Python
>>> one = MyClass() >>> two = MyClass() >>> one == two True >>> one is two True >>> id(one), id(two) (4303862608, 4303862608)
1
2
3
4
5
6
7
8
9
>>> one = MyClass ( )
>>> two = MyClass ( )
>>> one == two
True
>>> one is two
True
>>> id ( one ) , id ( two )
( 4303862608 , 4303862608 )
 

使用装饰器

我们知道,装饰器(decorator)可以动态地修改一个类或函数的功能。这里,我们也可以使用装饰器来装饰某个类,使其只能生成一个实例,代码如下:

Python
from functools import wraps def singleton(cls): instances = {} @wraps(cls) def getinstance(*args, **kw): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return getinstance @singleton class MyClass(object): a = 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from functools import wraps
 
def singleton ( cls ) :
     instances = { }
     @ wraps ( cls )
     def getinstance ( * args , * * kw ) :
         if cls not in instances :
             instances [ cls ] = cls ( * args , * * kw )
         return instances [ cls ]
     return getinstance
 
@ singleton
class MyClass ( object ) :
     a = 1
 

在上面,我们定义了一个装饰器 singleton,它返回了一个内部函数 getinstance,该函数会判断某个类是否在字典 instances 中,如果不存在,则会将 cls 作为 key,cls(*args, **kw) 作为 value 存到 instances中,否则,直接返回 instances[cls]

使用 metaclass

元类(metaclass)可以控制类的创建过程,它主要做三件事:

  • 拦截类的创建
  • 修改类的定义
  • 返回修改后的类

使用元类实现单例模式的代码如下:

Python
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] # Python2 class MyClass(object): __metaclass__ = Singleton # Python3 # class MyClass(metaclass=Singleton): # pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Singleton ( type ) :
     _instances = { }
     def __call__ ( cls , * args , * * kwargs ) :
         if cls not in cls . _instances :
             cls . _instances [ cls ] = super ( Singleton , cls ) . __call__ ( * args , * * kwargs )
         return cls . _instances [ cls ]
 
# Python2
class MyClass ( object ) :
     __metaclass__ = Singleton
 
# Python3
# class MyClass(metaclass=Singleton):
#    pass
 

小结

  • Python 的模块是天然的单例模式,这在大部分情况下应该是够用的,当然,我们也可以使用装饰器、元类等方法

http://funhacks.net/




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值