单例模式
单例模式是23种设计模式中比较简单的一类,整个过程中只有一个实例,所有生成的实例都指向同一块内存空间。
实现单例的四种方法
方法一
通过类的绑定方法
class Student:
info = None
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def get_info(cls):
if not cls.info:
cls.info = cls('wu', 18)
return cls.info
s1 = Student.get_info()
s2 = Student.get_info()
s3 = Student('xiaowu', 19)
print(s1)
print(s2)
print(s3)
方法二
通过装饰器
def get_info(cls):
info = cls('wu', 18)
def inner(*args, **kwargs):
if len(args) != 0 or len(kwargs) != 0:
res = cls(*args, **kwargs)
return res
else:
return info
return inner
@get_info
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student()
s2 = Student()
s3 = Student('xiaowu', 19)
print(s1)
print(s2)
print(s3)
方法三
通过元类
class Mymeta(type):
def __init__(self, name ,bases, dic):
self.info = self('wu', 18)
def __call__(self, *args, **kwargs):
if len(args) != 0 or len(kwargs) != 0:
obj = object.__new__(self)
obj.__init__(*args, **kwargs)
return obj
else:
return self.info
class Student(metaclass=Mymeta):
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student()
s2 = Student()
s3 = Student('xiaowu', 19)
print(s1)
print(s2)
print(s3)
方法四
通过模块导入。在python中,模块是天然的单例
# student.py(模块文件)
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student('wu', 18)
def test():
from student import s1
print(s1)
test()
from student import s1
from student import Student
s2 = Student('xiaowu', 19)
print(s1)
print(s2)
单例模式的优点
- 由于单例模式要求在全局只有一个实例,因而可以节省比较多的内存空间。
- 全局只有一个接入点,可以更好地进行数据同步控制,避免多重占用。
- 单例可长驻内存,减少系统开销。
单例模式的缺点
- 单例模式的扩展是比较困难的。
- 赋予了单例以太多的职责,某种程度上违反了单一职责原则。
- 单例模式是并发协作软件模块中需要最先完成的,因而其不利于测试。
- 单例模式在某种情况下会导致“资源瓶颈”。