单例模式

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

实现单例模式的四种方式

方式一: 通过调用类方法

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()

 

posted @ 2018-08-28 15:59  い年少有为  阅读(115)  评论(0编辑  收藏  举报