单例的多种实现方式

单例模式-个人理解:多次实例化结果指向同一个实例,简单的说的就是实例化对象之后,对象的id是否一样,实例化即使属性和方法都一样,也不能说明是同一个对象,在非单例情况下,即使属性和方法完全相同,对象也是在不同的堆栈中的。

具体实现方式如下:来源于网络,

第一种(基于classmethod)

复制代码
class Mysql(object):
    _instance = None

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

    @classmethod
    def singleton(cls):
        if not cls._instance:
            cls._instance = Mysql('127.0.0.1', 3306)
        return cls._instance


obj1 = Mysql.singleton()
obj2 = Mysql.singleton()
print(obj1)
print(obj2)
复制代码

第二种(基于装饰器)

复制代码
def singleton(cls):
    # 该对象在类Mysql被装饰上singleton的时候就已经实例化完毕
    _instance = cls('127.0.0.1',3306)
    def inner(*args,**kwargs):
        # 判断是否传入参数,传入参数表示要实例化新的,不传表示用默认的
        if args or kwargs:
            obj = cls(*args,**kwargs)
            return obj
        return _instance
    return inner

@singleton
class Mysql:
    def __init__(self,ip,port):
        self.ip = ip
        self.port = port

obj1 = Mysql()
obj2 = Mysql()
obj3 = Mysql()
print(obj1,obj2,obj3)
复制代码

第三种(基于元类)

复制代码
class MymetaClass(type):
    def __call__(self, *args, **kwargs):
        if not hasattr(self,'instance'):
            self.instance = super().__call__(*args,**kwargs)
        return self.instance

class Mysql(metaclass=MymetaClass):
    def __init__(self,host,port):
        self.host = host
        self.port = port
obj = Mysql('ajdak',213)
obj1 = Mysql('asdasdas',134234)
print(obj,obj1)
复制代码

第四种(基于__new__)

复制代码
class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kw):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)  
        return cls._instance  

class MyClass(Singleton):  
    a = 1
复制代码

第五种(基于模块)

复制代码
# 单独在一个py文件中定义一个类,并实例化一个对象,之后在其他文件导入这一对象,实现单例
class
Singleton(object): def __init__(self,host,port): self.host = host self.port = port singleton = Singleton('127.0.0.1',3306)
复制代码

单例模式是一种设计模式,实现单例模式的方式方法有很多,所以本文列出的只是其中的几种而已,不喜勿喷!

原文地址:https://www.cnblogs.com/Hale-wang/p/10824396.html