|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 °蓝鲤歌蓝 于 2019-1-27 10:42 编辑
各位小伙伴去面试时很有可能会被问到单例模式如何实现,现在就一起来看看吧。
- # -*-coding:utf-8-*-
- __Author__ = "Mr.D"
- __Date__ = '2019\1\27 0027 7:36'
- # __new__ 实现单例
- class Singleton():
- _instance = None
- def __new__(cls, *args, **kwargs):
- if not cls._instance:
- cls._instance = super(Singleton, cls).__new__(cls)
- return cls._instance
- s1 = Singleton()
- s2 = Singleton()
- print(s1 is s2)
- # 装饰器实现单例
- def Single(cls):
- _instance = {}
- def inner():
- if cls not in _instance:
- _instance[cls] = cls()
- return _instance[cls]
- return inner
- @Single
- class Singleton1():
- pass
- s1 = Singleton1()
- s2 = Singleton1()
- print(s1 is s2)
- # 元类实现单例
- class Metaclass(type):
- _instance = {}
- def __call__(cls, *args, **kwargs):
- if cls not in cls._instance:
- cls._instance[cls] = super().__call__()
- return cls._instance[cls]
- class Singleton2(metaclass=Metaclass):
- pass
- s1 = Singleton2()
- s2 = Singleton2()
- print(s1 is s2)
- # 类方法实现单例
- class Singleton3():
- _instance = None
- @classmethod
- def getInstance(cls):
- if not cls._instance:
- cls._instance = Singleton3()
- return cls._instance
- s1 = Singleton3.getInstance()
- s2 = Singleton3.getInstance()
- print(s1 is s2)
- # 特殊的单例:单态模式
- class Singleton4():
- _shared_state = {}
- def __new__(cls, *args, **kwargs):
- obj = super().__new__(cls, *args, **kwargs)
- obj.__dict__ = cls._shared_state
- return obj
- s1 = Singleton4()
- s2 = Singleton4()
- s1.x = 5
- print(s2.x)
- # 类装饰器实现单例
- class Single1():
- def __init__(self, cls):
- self._cls = cls
- self._instance = {}
- def __call__(self, *args, **kwargs):
- _cls = self._cls
- _instance = self._instance
- print(_instance)
- if _cls not in _instance:
- print(f'myinstance is {_instance}')
- _instance[self._cls] = _cls()
- return _instance[self._cls]
- class Singleton5():
- pass
- s1 = Singleton4()
- s2 = Singleton4()
- print(s1 is s2)
复制代码
|
|