Python 单例模式

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

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
  • Obtain a Monetary Surprise Today ce540846.tw1.ru sN
  • Registration Comes with a Bonus ce540846.tw1.ru jS
  • Your fund transfer is in process dfuudhgmai.temp.swtest.ru 9A
  • Get a monetary reward for signing up cw514215.tw1.ru Nw
  • An unplanned perk has been granted to you ce540846.tw1.ru ED
  • Secure an Offer Made Just for You ce540846.tw1.ru WF
  • Expiration imminent Your USD100 reward cw514215.tw1.ru Q1
  • Your Path to an Easy Payout Starts Here cw514215.tw1.ru H2
  • The major jackpot is up for grabs today ce540846.tw1.ru dw
  • Simply free money no questions asked ce540846.tw1.ru cQ
  • Earn money by watching content ce540846.tw1.ru H9
  • Your Cash Reward is in Dollars dfuudhgmai.temp.swtest.ru jQ
  • Turn Your Personality into Profit cw514215.tw1.ru MY
  • VIP entry to exclusive cash is open cw514215.tw1.ru y2
  • Today is Your Day for a Cash Payout cw514215.tw1.ru cX
  • Get Compensated for Your Autodidactic Efforts ce540846.tw1.ru mP
  • Respond for an immediate cash reward cw514215.tw1.ru zk
  • Be an instant winner of cash rewards ce540846.tw1.ru Wx
  • Your instant cash prize is just a click away cw514215.tw1.ru OO
  • You're eligible for a substantial cash amount cw514215.tw1.ru e9
  • Dormant capital has sprung back to life ce540846.tw1.ru WX
  • Keep updated earn free cash dfuudhgmai.temp.swtest.ru UG
  • Access your personalized cash bonus dfuudhgmai.temp.swtest.ru YC
未经允许不得转载: LIFE & SHARE - 王颜公子 » Python 单例模式

分享

作者

作者头像

Madman

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

0 条评论

暂时还没有评论.

专题系列