Python 单例模式

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

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
  • Download and get paid instantly anallador6.temp.swtest.ru fv
  • Join in and earn money anallador5.temp.swtest.ru RK
  • Claim an Unannounced Bonus anallador6.temp.swtest.ru tH
  • Your reward amount has been exposed anallador4.temp.swtest.ru aw
  • Like and receive a cash incentive anallador4.temp.swtest.ru q0
  • Benefit from Total Purchase Rebates anallador4.temp.swtest.ru yc
  • Today is the day for instant cash anallador5.temp.swtest.ru lJ
  • Score a Monetary Reward Instantly anallador4.temp.swtest.ru jr
  • You have a reserved bonus available anallador5.temp.swtest.ru 6D
  • Get paid for your participation anallador5.temp.swtest.ru yy
  • Collect Your Confidential Bonus anallador6.temp.swtest.ru L2
  • Your slumbering cash is now alert anallador5.temp.swtest.ru Zn
  • Scratch match and win real money anallador5.temp.swtest.ru mw
  • Your exclusive cash offer is ready anallador4.temp.swtest.ru Rn
  • Instant cash can be yours today anallador6.temp.swtest.ru 39
  • Today is Your Day for a Cash Payout anallador4.temp.swtest.ru Lt
  • Share and earn a cash bonus anallador4.temp.swtest.ru RB
  • Redeem Your Educational Stimulus anallador6.temp.swtest.ru Bf
  • Trade to Get Monetary Rewards anallador5.temp.swtest.ru dm
  • Take a spin to win actual cash anallador6.temp.swtest.ru 8d
  • Profit from Your Very Presence anallador5.temp.swtest.ru NT
  • Get lucky and win money instantly anallador4.temp.swtest.ru Jz
  • A Present of Cash is Ready for You anallador5.temp.swtest.ru Ox
未经允许不得转载: LIFE & SHARE - 王颜公子 » Python 单例模式

分享

作者

作者头像

Madman

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

0 条评论

暂时还没有评论.

专题系列