python设计模式之单列模式

python设计模式之单列模式

作用

  • 保证一个类仅有一个实例,并提供一个访问它的全局访问点

适用性

  • 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时
  • 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时

实例

  • 方式一
# -*- coding:utf-8 -*-

__author__ = 'Rick111'


class Singleton(object):
    """ 方式一 """
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            org = super(Singleton, cls)
            cls._instance = org.__new__(cls, *args, **kw)
        return cls._instance


class SingleSpam(Singleton):
    def __init__(self, s):
        self.s = s

    def __str__(self):
        return self.s


if __name__ == '__main__':
    s1 = SingleSpam('span')
    print id(s1), s1
    s2 = SingleSpam('spa')
    print id(s2), s2
    print id(s1), s1

output:
35885128 span
35885128 spa
35885128 spa
  • 方式二
# -*- coding:utf-8 -*-

__author__ = 'Ricky'


class Singleton(type):
    def __init__(cls, name, bases, dic):
        super(Singleton, cls).__init__(name, bases, dic)
        cls.instance = None

    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.instance

    def getInstance(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.instance


class SingleSpam(object):
    __metaclass__ = Singleton

    def __init__(self, s):
        self.s = s

    def __str__(self):
        return self.s


if __name__ == '__main__':
    s1 = SingleSpam('span')
    print id(s1), s1
    s2 = SingleSpam('spa')
    print id(s2), s2
    print id(s1), s1

output:
35153968 span
35153968 span
35153968 span
    原文作者:Ricky110
    原文地址: https://blog.csdn.net/Ricky110/article/details/77828956
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞