前置知识
什么是 Python 中的单例方法
单例方法是一种创建型设计模式,也是我们可用的最简单的设计模式之一。它是一种提供特定类型唯一对象的方式。它仅涉及一个类来创建方法并指定对象。
我们可以通过一个非常简单的数据库连接示例来理解单例设计模式。当每个对象都创建一个唯一的数据库连接时,将会极大地影响项目的成本和开销。因此,创建一个单一的连接总是比创建额外的无关连接要好,而这可以通过单例设计模式轻松实现。
!single-pattern-in-pythonsingleton-pattern
> 定义: 单例模式是一种限制类实例化只能有一个对象的设计模式。
现在让我们来看看单例设计模式的不同实现方式。
方法 1:单态/Borg 单例设计模式
单例行为可以通过 Borg 模式来实现,但该模式下不是只有一个类实例,而是有多个实例共享相同的状态。在这里,我们不关注实例身份的共享,而是关注状态的共享。
# Singleton Borg pattern
class Borg:
# state shared by each instance
__shared_state = dict()
# constructor method
def __init__(self):
self.__dict__ = self.__shared_state
self.state = ‘GeeksforGeeks‘
def __str__(self):
return self.state
# main method
if __name__ == "__main__":
person1 = Borg() # object of class Borg
person2 = Borg() # object of class Borg
person3 = Borg() # object of class Borg
person1.state = ‘DataStructures‘ # person1 changed the state
person2.state = ‘Algorithms‘ # person2 changed the state
print(person1) # output --> Algorithms
print(person2) # output --> Algorithms
person3.state = ‘Geeks‘ # person3 changed the
# the shared state
print(person1) # output --> Geeks
print(person2) # output --> Geeks
print(person3) # output --> Geeks
输出:
Algorithms
Algorithms
Geeks
Geeks
Geeks
!singleton-Design-pattern-pythonSingleton-Design-pattern
双重检查锁定 单例设计模式
很容易注意到,一旦创建了对象,线程的同步就不再有用,因为此时对象永远不会等于 None,任何操作序列都将导致一致的结果。
所以,只有当对象等于 None 时,我们才会获取 getInstance 方法上的锁。
# Double Checked Locking singleton pattern
import threading
class SingletonDoubleChecked(object):
# resources shared by each and every
# instance
__singleton_lock = threading.Lock()
__singleton_instance = None
# define the classmethod
@classmethod
def instance(cls):
# check for the singleton instance
if not cls.__singleton_instance:
with cls.__singleton_lock:
if not cls.__singleton_instance:
cls.__singleton_instance = cls()
# return the singleton instance
return cls.__singleton_instance
# main method
if __name__ == ‘__main__‘:
# create class X
class X(SingletonDoubleChecked):
pass
# create class Y
class Y(SingletonDoubleChecked):
pass
A1, A2 = X.instance(), X.instance()
B1, B2 = Y.instance(), Y.instance()
assert A1 is not B1
assert A1 is A2
assert B1 is B2
print(‘A1 : ‘, A1)
print(‘A2 : ‘, A2)
print(‘B1 : ‘, B1)
print(‘B2 : ‘, B2)
输出:
A1 :
A2 :
B1 :
B2 :
在 Python 中创建单例
在单例设计模式的经典实现中,我们简单使用静态方法来创建 getInstance 方法,该方法有能力返回共享资源。我们还利用所谓的虚拟私有构造函数来针对它引发异常,尽管这并不是必需的。
# classic implementation of Singleton Design pattern
class Singleton:
__shared_instance = ‘GeeksforGeeks‘
@staticmethod
def getInstance():
"""Static Ac