饿汉式单例模式实现预先加载,急切初始化,单例对象在类实例化前创建。
[Python] 纯文本查看 复制代码 class Singleton(object):
""" """
_instance = None
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
@classmethod
def get_instance(cls):
return cls._instance
@classmethod
def sum(cls, num1, num2):
print(Singleton._instance)
return num1 + num2
@staticmethod
def reduce(num1, num2):
print(Singleton._instance)
return num1 - num2
优点:
1. 线程安全
2. 在类实例化前已经创建好一个静态对象,调用时反应速度快
3. 直接执行其他方法或静态方法时,单例实例不会被初始化
缺点:
1. 不管使用与否,实例化前就初始化静态对象,有点资源浪费;
懒汉式单例模式实现
[Python] 纯文本查看 复制代码 class Singleton(object):
"""
# 懒汉模式: 只有在使用时才创建单例对象,实例化时不创建
"""
_instance = None
def __init__(self):
if not hasattr(Singleton, '_instance'):
print("__init__ method called, but no instance created")
else:
print("instance already created:", self._instance)
@classmethod
def get_instance(cls):
if not cls._instance:
cls._instance = Singleton()
return cls._instance
优点:
1. 资源利用合理,不调用 get_instance 方法不创建单例对象 缺点:
1. 线程不安全,多线程时可能会获取到不同单例对象的情况。解决办法是加互斥锁,但会降低效率 线程安全的单例
[Python] 纯文本查看 复制代码
import threading
def synchronized(func):
func.__lock__ = threading.Lock()
def lock_func(*args, **kwargs):
with func.__lock__:
return func(*args, **kwargs)
return lock_func
class Singleton(object):
instance = None
@synchronized
def __new__(cls, *args, **kwargs):
"""
:type kwargs: object
"""
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self, num):
self.a = num + 5
def printf(self):
print(self.a)
a = Singleton(3)
print(id(a))
b = Singleton(4)
print(id(b))
|