zoukankan      html  css  js  c++  java
  • 单例的三种实现方式

    一:类方法实现单例

    class Mysql:
        __instance = None
        def __init__(self,host,port):
            self.host = host
            self.port = port  q
        @classmethod
        def singleton(cls):
            if not cls.__instance:
                cls.__instance = cls(setting.host,setting.port)
            return cls.__instance
    obj1 = Mysql.singleton()
    obj2 = Mysql.singleton()
    print(obj1)
    print(obj2)

    二:自定制元类方法实现单例

    import setting
    class Mymeta(type):
        def __init__(self,class_name,base,dic):
            super().__init__(class_name, base, dic)#初始化一个类(mysql)
            self.__instance = object.__new__(self)#利用mysql类的基类__new__方法造出一个mysql类的对象
            self.__init__(self.__instance,setting.host,setting.port)#调用类的__init__方法实例化出这个对象
        def __call__(self, *args, **kwargs):
            #如果对元类的实例化对象mysql类加括号调用则自动触发,元类的对象类mysql会作为第一个参数自动传入
            #相当于mysql.__call__()
            if args or kwargs:
                obj = object.__new__(self)
                self.__init__(obj,*args,**kwargs)
                return obj
            return self.__instance
    class Mysql(metaclass=Mymeta):#定义类mysql(实际就是(调用元类的_init__方法))
        def __init__(self,host,port):
            self.host = host
            self.port = port
    obj1 = Mysql()#加括号调用,实例化生成对象(调用类的__init__方法)
    obj2 = Mysql()
    print(obj1)
    print(obj2)
    obj3 = Mysql("129.0.0.1",8080)
    obj4 = Mysql("129.0.0.1",8080)
    print(obj3)
    print(obj4)

    三:装饰器方法实现单例

    def sigleton(cls):
        __instance = cls(setting.host,setting.port)
        def wrapper(*args,**kwargs):
            if args or kwargs:
                # obj = cls(*args, **kwargs)
                obj = object.__new__(cls)
                cls.__init__(obj,*args, **kwargs)
                return obj
            return __instance
        return wrapper
    @sigleton
    class Mysql:
        def __init__(self,host,port):
            self.host = host
            self.port = port

    附:setting.py

    port = 8888
    host = "127.0.0.1"
  • 相关阅读:
    C#中async/await中的异常处理
    Xunit
    Markdown安装与简单使用
    .Net Ajax跨域请求总结
    centos 安装 Vmare tool
    linux安装Java
    linux常用命令整理
    autofac解析Mvc和Webapi的坑
    swarm on ubuntu
    deploy service on swarm
  • 原文地址:https://www.cnblogs.com/li1992/p/9152939.html
Copyright © 2011-2022 走看看