• 单例模式


    单例模式是一种设计模式一次只允许产生一个实例对象.

    实现方法有很多,常见的方法有五种:

    1.classmethod

    class Mysql:
        _instance = None
        def __init__(self,host,port):
            self.host = host
            self.port = port
        @classmethod
        def singleton(cls):
            if not cls.singleton:
                _instance = cls('127.0.0.1',3306)
            return cls._instance
    
    print(id(Mysql.singleton()))
    print(id(Mysql.singleton()))

    2.装饰器

    from functools import wraps
    def singleton(cls):
        cls._instance = cls('127.0.0.1',3306)
        @wraps(cls)
        def inner(*args,**kwargs):
            if args or kwargs:
                obj = cls(*args,**kwargs)
                return obj
            return cls._instance
        return inner
    
    
    @singleton  # Mysql = singleton(Mysql)
    class Mysql:
        def __init__(self,host,port):
            self.host = host
            self.port = port
    obj1 = Mysql()
    obj2 = Mysql()
    print(id(obj1),id(obj2))

    3.基于元类

    class MymetaClass(type):
        def __call__(self,*args,**kwargs):
            if not getattr(self,'_instance'):
                self._instance = super().__call__(*args,**kwargs)
            return self._instance
    
    class Mysql(metaclass = MymetaClass):
        _instance =None
        def __init__(self,host,port):
            self.host = host
            self.port = port
            
    print(id(Mysql('127.9.0.1',9090)))
    print(id(Mysql('127.9.0.2',9090)))

    4基于__new__

    class Singleton(object):
    
      _instance = None
    
      def __new__ (cls,*args,**kw):
    
        if not cls._instance:
    
          cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs)
    
          return cls._instance

    5基于模块(最常用!)

    # demo.py
    class Setting():
        pass
    
    settings = Setting()
    
    
    # start.py
    from demo import settings
    
    # settings被导入任何模块都是同一对象

    以上五种方法,模块最简单也最常用.

  • 相关阅读:
    filp_open/filp_close/vfs_read/vfs_write
    memcpy一种实现方法
    memset函数的实现&printf函数几种输出格式的输出结果
    break退出循环分析
    定义指针变量作为返回值函数执行时报 段错误(核心已转储)
    node实现防盗链
    js实现输入密码之延迟星号和点击按钮显示或隐藏
    rem适配
    使用字蛛教程以及遇到的bug
    es6学习笔记-proxy对象
  • 原文地址:https://www.cnblogs.com/gongcheng-/p/10599757.html
Copyright © 2020-2023  润新知