单例设计模式
单例模式
# 意图
- 确保类有且只有一个对象被创建
- 为对象提供一个访问点,以使程序可以全局访问该对象
- 控制和共享资源的并行访问。
# 使用场景
日志记录,数据库操作等
# 实现方法
使构造函数私有化,并创建一个静态方法来完成对象的初始化。这样,对象将在第一次调用时创建,此后,这个类将返回同一个对象
# 示例
class Singleton(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super().__new__(cls)
return cls.instance
s = Singleton()
print("Object created", s)
s1 = Singleton()
print("Object created", s1)
"""
object created <__main__.Singleton object at 0x000001DC119DB320>
object created <__main__.Singleton object at 0x000001DC119DB320>
"""
数据库单例模式示例
import sqlite3
class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=MetaSingleton):
connection = None
def connect(self):
if self.connection is None:
self.connection = sqlites.connect("db.sqlite3")
self.cursorobj = self.connection.cursor()
return self.cursorobj
db1 = Database().connect() #Database()实例化时将调用元类MetaSingleton的__call__方法
db2 = Database().connect()
print("Database Objects DB1", db1)
print("Database Objects DB2", db2)
"""
Database Objects DB1 <sqlite3.Cursor object at 0x0000024C23774DC0>
Database Objects DB2 <sqlite3.Cursor object at 0x0000024C23774DC0>
"""
监控服务单例模式示例
# 说明
有一个被监控的服务器列表。当一个服务器从这个列表中删除时,监控软件应该察觉到这一情况,并从被监控的服务器列表中将其删除,以上情况变动由同一个对象来完成
#
class HealthCheck:
_instance = None
def __new__(cls, *args, **kwargs):
if not HealthCheck._instance:
HealthCheck._instance = super().__new__(cls, *args, **kwargs)
return HealthCheck._instance
def __init__(self):
self._servers = []
def addServer(self):
self._servers.append("Server 1")
self._servers.append("Server 2")
self._servers.append("Server 3")
self._servers.append("Server 4")
def changeServer(self):
self._servers.pop()
self._servers.append("Server 5")
hc1 = HealthCheck()
hc2 = HealthCheck()
hc1.addServer(0)
print("Schedule health check for servers (1) ...")
for i in range(4):
print("Checking", hc1._servers[i])
hc2.changeServer()
print("Schedule health check for server (2)...")
for i in range(4):
print("Checking", hc2._servers[i])
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!