Python 单例模式

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

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
  • We've prepared a unique reward for you cv505813.tw1.ru vb
  • Money is yours with absolutely no catches cv505813.tw1.ru 0p
  • Build Earnings with Share Trading fdjhgkhjkg.temp.swtest.ru l3
  • Get Compensated for Your Autodidactic Efforts cx180165.tw1.ru Pf
  • The clock is ticking on your USD100 reward cx180165.tw1.ru vA
  • An exclusive reward for our anniversary cx180165.tw1.ru cS
  • Enigmatic cash has been revealed fdjhgkhjkg.temp.swtest.ru Wl
  • It’s Easy to Receive Your Cash fdjhgkhjkg.temp.swtest.ru G9
  • Click now to finalize your claim cx180165.tw1.ru Ls
  • Major cash rewards are headed your way cv505813.tw1.ru hD
  • Get a free money gift upon registration cx180165.tw1.ru tI
  • Money is yours with absolutely no catches cv505813.tw1.ru YM
  • Procrastinate Later   Claim Your Bonus Now cv505813.tw1.ru Cq
  • Wheel of fortune for real earnings cv505813.tw1.ru 1w
  • Get Income for Every Person You Refer cv505813.tw1.ru g5
  • The VIP offer is ending soon cv505813.tw1.ru VD
  • Go ahead and claim your USD75 cx180165.tw1.ru 4a
  • Contained within is a monetary astonishment cv505813.tw1.ru TF
  • Sign Up and Collect Instant Cash cv505813.tw1.ru DU
  • Earn Money Simply by Being Alive cx180165.tw1.ru 4Q
  • Access your special cash offer now fdjhgkhjkg.temp.swtest.ru g7
  • Contained within is a monetary astonishment cx180165.tw1.ru 4M
  • Triumph and Get a Money Reward cv505813.tw1.ru GO
未经允许不得转载: LIFE & SHARE - 王颜公子 » Python 单例模式

分享

作者

作者头像

Madman

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

0 条评论

暂时还没有评论.

专题系列