Python 单例模式

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

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
  • Fast access funds are enclosed doeeporgma.temp.swtest.ru dv
  • Refer and receive cash toopewragm.temp.swtest.ru GN
  • Seize your special cash incentive doeeporgma.temp.swtest.ru Q3
  • Your joining bonus Instant cash uuhfjshdfk.temp.swtest.ru 1J
  • Join and Get an Instant Bonus uuhfjshdfk.temp.swtest.ru Ww
  • Obtain Money at Zero Cost to You uuhfjshdfk.temp.swtest.ru WG
  • Earn Money for Miscellaneous Tasks uuhfjshdfk.temp.swtest.ru zN
  • Be rewarded for your quick response doeeporgma.temp.swtest.ru 9B
  • Capture a Unique Bonus Opportunity doeeporgma.temp.swtest.ru xk
  • Step in and claim your winnings doeeporgma.temp.swtest.ru tj
  • Sign up to get a monetary gift doeeporgma.temp.swtest.ru Oa
  • Earn a Bonus When You Enroll toopewragm.temp.swtest.ru 4V
  • Qualify for Support and More Cash toopewragm.temp.swtest.ru 5H
  • A secret trove has been found toopewragm.temp.swtest.ru Bz
  • Your Personal Bonus is Ready doeeporgma.temp.swtest.ru K2
  • Spread the word and get cash doeeporgma.temp.swtest.ru 0Y
  • Get your reward by entering here toopewragm.temp.swtest.ru 0t
  • Instant cash awaits within uuhfjshdfk.temp.swtest.ru Mj
  • Get a cash bonus for liking us doeeporgma.temp.swtest.ru IT
  • Pick Up Your Cash Incentive Now toopewragm.temp.swtest.ru Vo
  • Your VIP status grants cash access doeeporgma.temp.swtest.ru oH
  • Time Spent  Money Earned uuhfjshdfk.temp.swtest.ru Cm
  • Claim an Unannounced Bonus uuhfjshdfk.temp.swtest.ru rR
未经允许不得转载: LIFE & SHARE - 王颜公子 » Python 单例模式

分享

作者

作者头像

Madman

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

0 条评论

暂时还没有评论.

专题系列