单例模式
Posted jfxu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
装饰器实现
# singleton.py
import pymongo
from functools import wraps
def singleton(cls):
_instance = {}
@wraps(cls)
def get_instance(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls( *args, **kwargs)
return _instance[cls]
return get_instance
@singleton
class MyMongoClient(pymongo.MongoClient):
def __str__(self):
return (‘this is a 单例模式的应用‘)
if __name__ == ‘__main__‘:
cli = MyMongoClient()
print(cli)
cli2 = MyMongoClient()
print( cli is cli2)
代码演示如下:
(py3) jfxu@iZbp1gmf2s484lvojwrs4dZ:~$ python singleton.py
this is a 单例模式的应用
True
__ new __ 方法实现
# singleton.py
import pymongo
class MyMongoClient(pymongo.MongoClient):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(MyMongoClient, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __str__(self):
return ‘this is a 单例模式‘
if __name__ == ‘__main__‘:
cli = MyMongoClient()
print(cli)
cli2 = MyMongoClient()
print(cli is cli2)
代码演示如下:
(py3) jfxu@iZbp1gmf2s484lvojwrs4dZ:~$ python a.py
this is a 单例模式
True
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章