关于单例模式
Posted jec1999
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于单例模式相关的知识,希望对你有一定的参考价值。
#------------------------------------------------ 一 ----------------------------------------------------
"""
代码解释: class Singleton2中的__init__在MyClass2声明的时候被执行,MyClass2=Singleton2()
MyClass2()时,最先执行父类的__call__方法(object,Singleton2都作为MyClass2的父类,根据深度优先算法,会执行Singleton2中的__call__)
Singleton2中的__call__ 中书写了单例的逻辑.
"""
# class Singleton2(type):
# def __init__(self, name, bases, dict):
# print(self)
# print("sssss")
# super(Singleton2, self).__init__(name, bases, dict)
# self._instance = None
# def __call__(self, *args, **kwargs):
# print(self)
# if self._instance is None:
# self._instance = super(Singleton2, self).__call__(*args, **kwargs)
# return self._instance
#
#
# class MyClass2(object,metaclass=Singleton2):
# a = 1
#
# one = MyClass2()
# two = MyClass2()
#
# print (id(one)) # 31495472
#
# print (id(two)) # 31495472
#
# print (one == two) # True
#
# print (one is two) # True
#------------------------------------------------ 二 ----------------------------------------------------
# class Singleton(object):
# def __new__(cls, *args, **kwargs):
# if not hasattr(cls, ‘_instance‘):
# cls._instance = super().__new__(cls, *args, **kwargs)
# return cls._instance
#
#
# class MyClass(Singleton):
# a = 1
#
#
# one = MyClass()
# two = MyClass()
#
# # one和two完全相同,可以用id(), ==, is检测
# print (id(one))
# # 29097904
# print (id(two))
# # 29097904
# print (one == two)
# # True
# print (one is two )
# True
#------------------------------------------------ 三 ----------------------------------------------------
# def singleton(cls):
# instances = {}
#
# def _singleton(*args, **kwargs):
# if cls not in instances:
# instances[cls] = cls(*args, **kwargs)
# return instances[cls]
#
# return _singleton
#
#
# @singleton # MyClass3 = singleton(MyClass3)
# class MyClass3(object):
# a = 1
# def __init__(self,*args, **kwargs):
# pass
#
# one = MyClass3(3,4,5) # MyClass3:<function singleton.<locals>._singleton at 0x000000170E460D08>
# two = MyClass3(6,7,i=9)
#
# print (id(one))
# # 29660784
# print (id(two))
# # 29660784
# print (one == two)
# # True
# print (one is two)
# True
#------------------------------------------------ 三(自己练习) ----------------------------------------------------
def singleton(cls):
instances={}
def _singleton(*args,**kwargs):
if cls not in instances:
instances[cls]=cls(*args,**kwargs)
return instances[cls]
return _singleton
@singleton
class MyClass(object):
a = 1
def __init__(self,*args,**kwargs):
pass
a = MyClass(1,2)
b = MyClass(2,4,i=5)
print(id(a))
print(id(b))
#------------------------------------------------ 四,基于文件实现 ----------------------------------------------------
class XXX(object):
pass
xx = XXX() #---->这样别的地方从本模块直接导入xx,他们的id都是一样
以上是关于关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章