1、什么是单例模式
-
一个类只能实例化一个对象的设计模式称为单例模式。
-
单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
class People(object):
pass
p1 = People() # object
p2 = People() # object
print(p1, p2) # 每个对象的内存地址不同,肯定不是单例模式
输出:
<__main__.People object at 0x000001E5F96D8580> <__main__.People object at 0x000001E5F96D8760>
2、基于装饰器实现的单例模式
from functools import wraps
## 生成装饰器
def singleton(cls):
# 通过一个字典存储类和对象信息{"Class":"object"}
instances = {}
@wraps(cls)
def wrapper(*args, **kwargs):
# 为了保证单例模式, 判断该类是否已经实例化为对象
# 1. 如果有对象,直接返回存在的对象
# 2. 如果没有则实例化对象, 并存储类和对象到字典中, 最后返回对象
if instances.get(cls):
return instances.get(cls)
object = cls(*args, **kwargs)
instances[cls] = object
return object
return wrapper
@singleton
class People(object):
pass
p1 = People()
p2 = People()
print(p1,p2)
print(p1 is p2) ## true 为单例模式
3、基于new方法实现的案例模式
_ _new_ _ 方法是在实例化对象之前执行的内容
_ _init_ _ 方法是在实例化对象之后执行的内容
class People(object):
_instance = None
def __new__(cls, *args, **kwargs):
"""创建对象之前执行的内容"""
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self):
"""实例化对象之后执行, 将属性和对象封装在一起"""
print("正在执行构造方法init......")
p1 = People()
p2 = People()
print(p1, p2)
print(p1 is p2) ## true是单例模式
输出:
正在执行构造方法init......
正在执行构造方法init......
<__main__.People object at 0x000002534DEE8760> <__main__.People object at 0x000002534DEE8760>
True