Python实现单列模式

1. __ new __

class Borg(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            ob = super(Borg, cls)

            cls._instance = ob.__new__(cls, *args, **kwargs)

        return cls._instance


class MyClass(Borg):
    def __init__(self):
        self.a = 1


if __name__ == '__main__':
    a1 = MyClass()
    a2 = MyClass()

    a1.a = 10
    print(a1.a)
    print(a2.a)
    print(a1.__dict__)
  • 执行结果

10
10
{'a': 10}

2. 共享属性

class Borg(object):
    _state = {}

    def __new__(cls, *args, **kwargs):
        ob = super(Borg, cls).__new__(cls, *args, **kwargs)
        ob.__dict__ = cls._state

        return ob


class MyClass(Borg):
    def __init__(self):
        self.a = 1


if __name__ == '__main__':
    a1 = MyClass()
    a2 = MyClass()

    a1.a = 10
    print(a1.a)
    print(a2.a)
    print(a1.__dict__)

  • 执行结果

10
10
{'a': 10}

3. 装饰器

# 使用装饰器实现单例模式
def singleton(cls, *args, **kwargs):
    # 定义了一个私有的列表属性,来判断实例对象的是否存在,用于实例对象的创建
    instance = {}

    def _instance():
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)

        return instance[cls]

    return _instance


@singleton
class Test_singleton(object):
    def __init__(self):
        self.num = 0

    def add(self):
        self.num = 99


ts1 = Test_singleton()
ts2 = Test_singleton()

print(ts1)
print(ts2)
"""
可以使用类,实现装饰器的创建__call__方法
"""
  • 执行结果

<main.Test_singleton object at 0x104103668>
<main.Test_singleton object at 0x104103668>

4. import方法

# mysingleton .py
class MyClass(object):
    def __init__(self):
        self.a = 1

s_myclass = MyClass()
# to use
from mysingleton import s_myclass

s_myclass.a

你可能感兴趣的:(Python实现单列模式)