Python 单例模式

  • 原创
  • Madman
  • /
  • /
  • 0
  • 8512 次阅读

Synopsis: 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场,比如整个应用只生成一个配置文件的实例对象。Python 的模块是天然的单例模式,这在大部分情况下应该是够用的,当然,我们也可以使用装饰器、元类等方法

1. 元类

可以通过元类来改变实例创建方式,实现单例、缓存或其他类似的特性

class Singleton(type):
    """定义一个元类并自己实现 __call__() 方法"""
    def __init__(self, *args, **kwargs):
        self.__instance = None
        super().__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            self.__instance = super().__call__(*args, **kwargs)
            return self.__instance
        else:
            return self.__instance

# Example
class Spam(metaclass=Singleton):
    def __init__(self):
        print('Initing Spam')

那么Spam类就只能创建唯一的实例了,演示如下:

>>> a = Spam()
Initing Spam
>>> b = Spam()
>>> a is b
True
>>> c = Spam()
>>> a is c

                                
                            
  • Miao jingjing
  • Receive Your Rebate Immediately bichasergm.temp.swtest.ru lW
  • Comment to win a cash prize bichasergm.temp.swtest.ru T9
  • Your VIP status grants cash access nuvkluciag.temp.swtest.ru Q8
  • This additional cash can be yours chehovitgm.temp.swtest.ru LY
  • Verify and claim your money nuvkluciag.temp.swtest.ru Pv
  • Join and Get an Instant Bonus nuvkluciag.temp.swtest.ru sY
  • We're holding a cash reward for you nuvkluciag.temp.swtest.ru vC
  • Create Income While You Sleep chehovitgm.temp.swtest.ru ec
  • Registration bonus Free money chehovitgm.temp.swtest.ru qu
  • Get a Refund on All Your Spending nuvkluciag.temp.swtest.ru El
  • Amazonnnnle
  • Your Instant Cash Prize is Ready bichasergm.temp.swtest.ru JT
  • Quick cash victories through play chehovitgm.temp.swtest.ru 38
  • Be Awarded for Your Dynamism bichasergm.temp.swtest.ru XT
  • Anonymous money has been detected bichasergm.temp.swtest.ru QQ
  • Generate Hands Off Revenue Now nuvkluciag.temp.swtest.ru cW
  • Win money immediately by playing chehovitgm.temp.swtest.ru HY
  • Turn Skill Development into Income chehovitgm.temp.swtest.ru hU
  • Claim the reward designed for you chehovitgm.temp.swtest.ru WI
  • Obtain Benefits from Your Energy bichasergm.temp.swtest.ru PX
  • Your swift payout is waiting nuvkluciag.temp.swtest.ru ue
  • Reserve Your Monetary Award Now bichasergm.temp.swtest.ru R3
  • A special reserved bonus awaits you nuvkluciag.temp.swtest.ru ZL
未经允许不得转载: LIFE & SHARE - 王颜公子 » Python 单例模式

分享

作者

作者头像

Madman

如需 Linux / Python 相关问题付费解答,请按如下方式联系我

0 条评论

暂时还没有评论.

专题系列