单例模式的四种方式

介绍单例模式

  1. 内容 ----->保证一个类只有一个实例,并提供一个访问他的全局访问点
  2. 角色------>单例
  3. 使用场景---->当类只有一个实例,而且客户可以从一个众所周知的访问点访问他是时,比如数据库连接,socket创建连接
  4. 优点--->对唯一的实例的授权访问,单例相当于全局变量,有效防止了命名空间被污染

      与单例模式功能相似的概念  ,全局变量,静态变量(方法)

   为什么使用单例模式,不适用全局变量呢?

    答:全局变量可能会有名称空间的干扰,如有重名可能会被覆盖

单例模式实现的四种方式

1  文件导入的方式(常用)

######s1.py
class Foo(object):
def test(self):
print(123)
v = Foo() #实例

###### s2.py
# from s1 import v as v1
# print(v1,id(v1)) #<s1.Foo object at 0x0000000002221710> 35788560

# from s1 import v as v2 ##<s1.Foo object at 0x0000000002221710> 35788560
# print(v1,id(v2))
# 两个的内存地址是一样的
# 文件加载的时候,第一次导入后,再次导入时不会再重新加载。

2基于类实现的单例模式

# ======================单例模式:无法支持多线程情况===============


class Singleton(object):
    def __init__(self):
        import time
        time.sleep(1)


    @classmethod     #类方法
    def instance(cls,*args,**kwargs):
        if not hasattr(Singleton,"_instance"):
            Singleton.__instance = Singleton(*args,**kwargs)   #类变量   实例化一个对象
        return  Singleton.__instance



import threading

def task(arg):
    obj = Singleton.instance()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()

3、基于__new__实现的单例模式(最常

# =============单线程下执行===============
import threading
class Singleton(object):

    _instance_lock = threading.Lock()
    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    # 类加括号就回去执行__new__方法,__new__方法会创建一个类实例:Singleton()
                    Singleton._instance = object.__new__(cls)  # 继承object类的__new__方法,类去调用方法,说明是函数,要手动传cls
        return Singleton._instance  #obj1
        #类加括号就会先去执行__new__方法,在执行__init__方法
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)

# ===========多线程执行单利============
def task(arg):
    obj = Singleton()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()


# 使用先说明,以后用单例模式,obj = Singleton()
# 示例
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)

4、基于metaclass(元类)实现的单例模式

""
1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)

# 第0步: 执行type的 __init__ 方法【类是type的对象】
class Foo:
    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):
        pass
"
# 第1步: 执行type的 __call__ 方法
#        1.1  调用 Foo类(是type的对象)的 __new__方法,用于创建对象。
#        1.2  调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj = Foo()
# 第2步:执行Foo的 __call__ 方法
obj()
"""

# ===========类的执行流程================
class SingletonType(type):
    def __init__(self,*args,**kwargs):
        print(self)  #会不会打印?  #<class '__main__.Foo'>
        super(SingletonType,self).__init__(*args,**kwargs)

    def __call__(cls, *args, **kwargs):  #cls = Foo
        obj = cls.__new__(cls, *args, **kwargs)
        obj.__init__(*args, **kwargs)
        return obj


class Foo(metaclass=SingletonType):
    def __init__(self,name):
        self.name = name
    def __new__(cls, *args, **kwargs):
        return object.__new__(cls, *args, **kwargs)
'''
    1、对象是类创建的,创建对象时类的__init__方法会自动执行,对象()执行类的__call__方法
    2、类是type创建的,创建类时候type类的__init__方法会自动执行,类()会先执行type的__call__方法(调用类的__new__,__init__方法)
    Foo 这个类是由SingletonType这个类创建的
'''
obj = Foo("hiayan")


# ============第三种方式实现单例模式=================
import threading

class SingletonType(type):
    _instance_lock = threading.Lock()
    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            with SingletonType._instance_lock:
                if not hasattr(cls, "_instance"):
                    cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
        return cls._instance

class Foo(metaclass=SingletonType):
    def __init__(self,name):
        self.name = name


obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)

 装饰器实现的单例模式

#
def wrapper(cls):
    instance = {}
    def inner(*args,**kwargs):
        if cls not in  instance:
            instance[cls] = cls(*args,**kwargs)
        return instance[cls]
    return inner

@wrapper
class Singleton(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

obj1 = Singleton('haiyan',22)
obj2 = Singleton('xx',22)
print(obj1)
print(obj2)

 

posted @ 2018-12-24 22:09  团子emma  阅读(108)  评论(0)    收藏  举报