码迷,mamicode.com
首页 > 其他好文 > 详细

实现单例的四种实现方法

时间:2019-05-04 14:49:25      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:理解   结果   文件中   meta   pass   空间   需求   文件   更改   

# <单例>
# Singleton
#
# 单例:即单个实例,指的是同一个类实例化多次的结果指向同一个对象,用于节省内存空间
# 如果我们从配置文件中读取配置来进行实例化,在配置相同的情况下,就没必要重复产生对象浪费内存了
#
#     实现原理,为了节省空间,结合需求让同一个类多次实例化后结果指向同一个对象
#     可理解为开关,一次进入后更改 instance的状态

+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+

<< 1.类方法实现 >>

class Singleton:
    __instance = None
    def change_instance(cls):
        if not cls.__instance:
            cls.__instance = cls()
        return cls.__instance

+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+

<< 2.装饰器实现 >>

def outer(fn):
    _instance = None
    def inner(*args, **kwargs):
        nonlocal _instance
        if _instance == None:
            _instance = fn(*args, **kwargs)
        return _instance
    return inner

@outer
class Music:
    pass

+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+

<< 3.元类方法实现 >>

class SingleMeta(type):
    __instance = None
    def __call__(cls, *args, **kwargs):
        if SingleMeta.__instance == None:
            SingleMeta.__instance = object.__new__(cls) # {}
            cls.__init__(SingleMeta.__instance, *args, **kwargs)
            print(SingleMeta.__instance.__dict__) # {} {‘name‘: ‘egon‘}
        return SingleMeta.__instance

class Songs(metaclass=SingleMeta):
    def __init__(self):
        self.name = egon
    pass

+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+

<< 4.反射方法实现 >>

class Singleton(object):
  def __new__(cls):
    if not hasattr(cls, instance):
      cls.instance = super().__new__(cls)
    return cls.instance

+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+

 

实现单例的四种实现方法

标签:理解   结果   文件中   meta   pass   空间   需求   文件   更改   

原文地址:https://www.cnblogs.com/max404/p/10808298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!