Python 单例模式

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

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
  • Gather Your Virtual Clothing co066802.tw1.ru uU
  • Reach Your Best-Level Prize co066802.tw1.ru Xu
  • Pick Up Your Winnings ponapos.page.gd C2
  • Grab Hold of Your Monetary Present ponapos.page.gd 6m
  • Accept Your Big Six Wheel Funds co066802.tw1.ru le
  • Accept Your Money Right Away ponapos.page.gd P2
  • Receive Your Protected Money co066802.tw1.ru K6
  • Cash Out Your Ultimate Prize co066802.tw1.ru CW
  • Redeem Your Web3 Bonus cd096535.tw1.ru TY
  • Delight in Your Observed-and-Confirmed Money co066802.tw1.ru wU
  • Claim Your Foremost Cash cd096535.tw1.ru Pp
  • Obtain Your Bonus Cash ponapos.page.gd 3G
  • Open Your Baccarat Funds co066802.tw1.ru sx
  • Cash Out Your Funds Immediately ponapos.page.gd ag
  • Obtain Your Enjoyable Rounds cd096535.tw1.ru 2A
  • Open Your Top-Tier Prize cd096535.tw1.ru 7v
  • Exchange Your Signed-and-Verified Prize ponapos.page.gd kX
  • Unlock Your Senary Bonus co066802.tw1.ru id
  • Right Away Receive Your Prize co066802.tw1.ru cR
  • Claim Your Ultimate Reward co066802.tw1.ru PZ
  • Start Your Remunerative-Game Extra ponapos.page.gd e3
  • Accept Your Refined Funds cd096535.tw1.ru LK
  • Secure Your Bonus Rounds ponapos.page.gd ZF
未经允许不得转载: LIFE & SHARE - 王颜公子 » Python 单例模式

分享

作者

作者头像

Madman

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

0 条评论

暂时还没有评论.

专题系列