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
    

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

    请自行脑补实现过程

  • 相关阅读:
    用Total Commander for Android管理应用程序
    我的zsh简单设置
    C# Newtonsoft.Json 使用
    Wireshark 抓包 test
    C# 调用API test
    C# 委托 的语法 之一
    C# 对象初始化器 和数组初始化语法
    C 语言 数据类型长度
    vue 使用 test
    test
  • 原文地址:https://www.cnblogs.com/17vv/p/11459663.html
Copyright © 2011-2022 走看看