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

    四种方式实现单例模式

    一、类内部定义静态方法

    IP = '127.0.0.1'
    PORT = 3306
    
    class MySQL:
        _instance = None
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
        
        @classmethod
        def from_conf(cls):
            if not _instance:
                cls._instance = cls(IP, PORT)
            return cls._instance
    

    二、装饰器实现单例模式

    def singleton(cls):
        cls.__instance = cls(IP, PORT)
        
        def wrapper(*args, **kwargs):
            if len(args) == 0 and kwargs == 0:
                return cls.__instance
        	
            return cls(*args, **kwargs)
       
    @singleton
    class MySQL:
        def __init__(self, ip, port):
            self.ip = ip
            self.prot = port
    

    三、通过元类实现单例模式

    class Mymate(type):
        def __init__(self, name, bases, dic):
            self.__instance = self(IP, PORT)
        def __call__(self, *args, **kwargs):
            if len(args) == 0 and len(kwargs) == 0:
                return self.__instance
           	obj = object.__new__(cls)
            obj.__init__(self, *args, **kwargs)
            return obj
    

    四、通过模块导入的方式实现单例

    请自行脑补实现过程

  • 相关阅读:
    常用模块Part(1)
    递归函数
    python 生成器函数
    python 迭代器与生成器
    python 函数进阶
    python 装饰器进阶
    python time模块
    python 初始函数
    python 文件操作
    python 一些小知识
  • 原文地址:https://www.cnblogs.com/17vv/p/11459663.html
Copyright © 2011-2022 走看看