共计 1935 个字符,预计需要花费 5 分钟才能阅读完成。
一、单例概述
-
单例
是一种软件设计模式,该模式的主要目的是让一个类只能实例化一个对象
-
单例类
在一个程序中只能实例化一个对象的类称为单例类
-
设计模式
前人总结的使用方案,我们现在可以直接使用,大约 23 种
-
实现方式
- 模块
__new__
- 装饰器实现
- 元类
二、使用模块实现单例
-
原理
python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成.pyc 文件,当第二次导入时,就会直接加载.pyc 文件,而不会再次执行模块代码。因此我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了
-
银行卡类(card.py)
class BankCard(object): def __init__(self, cardId, passwd, money): self.cardId = cardId self.passwd = passwd self.money = money card = BankCard("888888", "888888", 1000)
-
丈夫类(husband.py)
from bankCard import card class Husband(object): def play(self): print(card.money)
-
妻子类(wife.py)
from bankCard import card class Wife(object): def face(self): card.money -= 100
-
主文件(main.py)
from wife import Wife from husband import Husband def main(): w = Wife() h = Husband() w.face() h.play() if __name__ == "__main__": main()
三、使用 __new__
实现单例
-
银行卡类(card.py)
class BankCard(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, "instance"): # 调用父类中的__new__()得到混沌对象 cls.instance = super().__new__(cls) return cls.instance def __init__(self): self.cardId = "88888888" self.passwd = "88888888"
-
丈夫类(husband.py)
from bankCard import BankCard class Husband(object): def play(self): card = BankCard() print(card.money)
-
妻子类(wife.py)
from bankCard import BankCard class Wife(object): def face(self): card = BankCard() card.money = 1000 card.money -= 100
-
主文件(main.py)
from wife import Wife from husband import Husband def main(): w = Wife() h = Husband() w.face() h.play() if __name__ == "__main__": main()
四、使用装饰器实现单例
-
银行卡类(card.py)
def single(cls): # Person:obj,A:obj instance = {} def inner(*args, **kwargs): if cls not in instance: instance[cls] = cls(*args, **kwargs) return instance[cls] return inner @single class BankCard(object): def __init__(self): self.cardId = "88888888" self.passwd = "88888888" self.money = 1000 @single class A(object): pass
-
丈夫类(husband.py)
from bankCard import BankCard class Husband(object): def play(self): card = BankCard() print(card.money)
-
妻子类(wife.py)
from bankCard import BankCard class Wife(object): def face(self): card = BankCard() card.money -= 200
-
主文件(main.py)
from wife import Wife from husband import Husband def main(): w = Wife() h = Husband() w.face() h.play() if __name__ == "__main__": main()
正文完
星哥玩云-微信公众号