zoukankan      html  css  js  c++  java
  • 单例模式

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

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

    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被导入任何模块都是同一对象

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

  • 相关阅读:
    【转】机器学习算法一览,应用建议与解决思路
    机器学习笔记04(Logistic Regression)
    机器学习笔记03(Classification: Probabilistic Generative Model)
    机器学习笔记00(课程结构)
    .Net PE
    wpf 画五角星函数
    .Net Core CLR FileFormat Call Method( Include MetaData, Stream, #~)
    天子守国门,君王死社稷
    CoreCLR Host源码分析(C++)
    Core CLR Host 源码简单分析
  • 原文地址:https://www.cnblogs.com/gongcheng-/p/10599757.html
Copyright © 2011-2022 走看看