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

    单例模式:多次实例化的结果指向同一个实例
    单例模式的作用:减少内存空间的使用

    实现单例模式的四种方式

    方式一: 通过调用类方法

    class Mysql:
        _instance = None
    
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
        @classmethod
        def form_conf(cls):
            if not cls._instance:
                cls._instance = cls("1.1.1.1", 3306)
            return cls._instance


    方式二:通过装饰器

    def single(cls):
        _instance = cls("1.1.1.1", 3306)
    
        def wrapper(*args, **kwargs):
            if args or kwargs:
                instance = cls(*args, **kwargs)
                return instance
            else:
                return _instance
    
        return wrapper
    
    
    @single
    class Mysql:
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port


    方式三:通过元类

    class Meta(type):
        def __init__(self, class_name, class_bases, class_dic):
            self.class_name = class_name
            self.class_bases = class_bases
            self.class_dic = class_dic
            self._instance = self("1.1.1.1", 3306)
    
        def __call__(self, *args, **kwargs):
            if args or kwargs:
                obj = self.__new__(self)
                self.__init__(obj, *args, **kwargs)
                return obj
            else:
                return self._instance
    
    
    class Mysql(metaclass=Meta):
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port


    方式四:通过模块

    模块代码

    class Mysql:
        def __init__(self, ip, port):
            self.ip = ip
            self.port = port
    
    
    instance = Mysql("1.1.1.1", 3306)

    执行代码

    def f2():
        from single import instance
        print(instance)
    
    
    def f3():
        from single import instance
        print(instance)
    
    
    def f4():
        from single import Mysql
        instance = Mysql("1.1.1.2", 3302)
        print(instance)
    
    f1()
    f2()
    f3()
    f4()
  • 相关阅读:
    Qt内存回收机制
    Qt坐标系统
    Qt信号与槽的使用
    Qt初始化代码基本说明
    Qt下载、安装及环境搭建
    搭建CentOs7的WebServer
    Laying out a webpage is easy with flex
    Let's write a framework.
    使用go语言开发一个后端gin框架的web项目
    个人总结的J2EE目前知道的涵盖面,从大方向入手,多写单元测试,加强基础
  • 原文地址:https://www.cnblogs.com/liangchengyang/p/9548801.html
Copyright © 2011-2022 走看看