• Python单例模式的实现方式


    一.单例类

    单例模式(Singleton Pattern)是 Python 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

    这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

    注意点:

    • 1、单例类只能有一个实例。
    • 2、单例类必须自己创建自己的唯一实例。
    • 3、单例类必须给所有其他对象提供这一实例。

    二.单例模式实现方式

    # 1.使用__new__方法实现:
    class MyTest(object): _instance = None def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super().__new__(cls, *args, **kw) return cls._instance
    class Mytest(MyTest): a = 1

    # 结果如下
    >>> a = MyTest()
    >>> b = MyTest()
    >>> a == b
    True
    >>> a is b
    True
    >>> id(a), id(b)
    (2339876794776,2339876794776)
     
     
    # 2.装饰器方式实现
    def outer(cls, *args, **kw):
    instance = {}

    def inner():
    if cls not in instance:
    instance[cls] = cls(*args, **kw)
    return instance[cls]

    return inner


    @outer
    class Mytest(object):
    def __init__(self):
    self.num_sum = 0

    def add(self):
    self.num_sum = 100
    # 结果如下
    >>> a = MyTest()
    >>> b = MyTest()
    >>> id(a), id(b)
    (1878000497048,1878000497048)
    # 3.使用元类实现
    class Mytest(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
    if cls not in cls._instances:
    cls._instances[cls] = super().__call__(*args, **kwargs)
    return cls._instances[cls]

    # Python2
    class MyTest(object):
    __metaclass__ = Mytest


    # Python3
    class MyTest(metaclass=Mytest):
      pass
    >>> a = MyTest()
    >>> b = MyTest()
    >>> id(a), id(b)
    (1878000497048,1878000497048)
    博文纯属个人思考,若有错误欢迎指正!
  • 相关阅读:
    洛谷 P1024 一元三次方程求解
    洛谷 P1025 数的划分
    假期一测
    洛谷 P1032 字符变换
    洛谷 P1033 自由落体
    洛谷 P1063 能量项链
    洛谷 P1072 Hankson 的趣味题
    洛谷 P1040 加分二叉树
    1013: [JSOI2008]球形空间产生器sphere
    1013: [JSOI2008]球形空间产生器sphere
  • 原文地址:https://www.cnblogs.com/yushenglin/p/10918983.html
Copyright © 2020-2023  润新知