1.什么是单例设计模式
它是一种机制,确保类有且只有一个特定的类型的对象,并提供全局的访问点。例如:日志记录、打印机后台处理、数据库连接等。
它的设计意图:
- 确保类有且只有一个对象被创建
- 为对象提供一个访问店,以使得程序可以全局访问该对象
- 控制共享资源的并行访问
优点:
避免同一资源产生相互冲突的请求。例如,同时User1删除某一数据后,User2更新它。
2.代码实现:
这里给出多种实现方式:
a.经典法:
通过hasattr判断当前是否有这个实例
class Singleton1(object):
def __new__(cls):
# 判断cls没有这个属性
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton1, cls).__new__(cls)
return cls.instance
s1_0 = Singleton1()
print("Object create is: ", s1_0)
s1_1 = Singleton1()
print("Object create is: ", s1_1)
b.懒汉式:
通过__instance 判断当前是否有这个实例(创建时,直接构建它)
class Singleton2(object):
__instance = None
def __init__(self):
if not Singleton2.__instance:
print("__init__ method called !")
else:
print("Instance already create:", self.genInstance())
@classmethod
def genInstance(cls):
if not cls.__instance:
cls.__instance = Singleton2()
return cls.__instance
s2_0 = Singleton2()
print("Object create is: ", s2_0)
s2_1 = Singleton2()
print("Object create is: ", s2_1)
c.Monstate实现单例:
这个方法共享状态,通过创建 dict。
class Borg(object):
__share_state = {"1": "2"}
def __init__(self):
self.x = 1
self.__dict__ = self.__share_state
pass
b = Borg()
b1 = Borg()
b.x = 4
print("Borg Object 'b': ", b)
print("Borg Object 'b1': ", b1)
print("Object state 'b': ", b.__dict__)
print("Object state 'b1': ", b1.__dict__)
d.利用元类实现单例:
这个方法最重要
# 每次创建对象的时候,调用python的特殊方法__call__()
class MetaSingleton(type):
_instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
print(cls) # 证明只创建一次
cls._instance[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
return cls._instance[cls]
class Logger(metaclass=MetaSingleton):
pass
logger1 = Logger()
logger2 = Logger()
print("Logger Object 'logger1': ", logger1)
print("Logger Object 'logger2': ", logger2)
3.实际应用:
这里给出多种实现方式:
a.调用数据库
# 1.调用数据库
import sqlite3
class DataBase(metaclass=MetaSingleton):
connection = None
def connect(self):
if self.connection is None:
self.connection = sqlite3.connect('db.sqlite3')
self.cursorobj = self.connection.cursor()
return self.cursorobj
db1 = DataBase().connect()
db2 = DataBase().connect()
print(db1)
print(db2)
b.基础平台运行管理
class HealthCheck(metaclass=MetaSingleton):
def __init__(self):
self._servers = []
def addServer(self):
self._servers.append("Server 1")
self._servers.append("Server 2")
self._servers.append("Server 3")
def changeServer(self):
self._servers.pop()
self._servers.append("Server 4")
hc1 = HealthCheck()
hc2 = HealthCheck()
hc1.addServer()
print(hc1._servers)
hc2.changeServer()
hc2.changeServer()
print(hc2._servers)
4.源码:
https://github.com/Wind0ranger/LeetcodeLearn/blob/master/0-DesignPatterns/1-SingleTon.py
网友评论