Python几种方式实现单例模式
程序员文章站
2022-07-14 08:46:27
...
encoding:utf-8
author = 'zhoupao'
date = '2018/7/7 21:47'
方法一:
使用new方法实现单例模式
class SingleTon(object):
_instance = {}
def new(cls,args,kwargs):
if cls not in cls._instance:
cls._instance[cls]=super(SingleTon,cls).new(cls,args,**kwargs)
#一定要返回
return cls._instance[cls]
class Myclass(SingleTon):
class_val=20
def __init__(self,a):
self.a=a
if name == 'main':
mycls1=Myclass(1)
mycls2=Myclass(1)
print(mycls1 is mycls2)
方法二:
from functools import wraps
装饰器是以类当做形式参数传递过去
def single_ton(cls):
_instance ={}
@wraps(cls)
def single(*args,**kwargs):
if cls not in _instance:
_instance[cls]=cls(*args,**kwargs)
# 这里也一定要返回
return _instance[cls]
return single