zoukankan      html  css  js  c++  java
  • 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)
    博文纯属个人思考,若有错误欢迎指正!
  • 相关阅读:
    Centos7安装docker
    Centos 7快速安装之packstack
    mysql基础知识复习
    Linux系统部署samba服务记录
    简单python程序练习
    Docker 搭建pxc集群 + haproxy + keepalived 高可用(二)
    Docker 搭建pxc集群 + haproxy + keepalived 高可用(一)
    linux下的find文件查找命令与grep文件内容查找命令
    db2创建nickname
    oracle 启动报ORA-01105 ORA-19808
  • 原文地址:https://www.cnblogs.com/yushenglin/p/10918983.html
Copyright © 2011-2022 走看看