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

    单例模式四种方式

    单例模式:单例模式就是一个单个实例公用一个对象

    1.文件导入(比较常用)

    2.基于类

    无法支持多线程

    import threading
    
    class Singleton(object): 
        def __init__(self):
            pass
        @classmethod 
        def instance(cls, *args, **kwargs): 
            if not hasattr(Singleton, "_instance"): 
                Singleton._instance = Singleton(*args, **kwargs) 
        return Singleton._instance
        
    obj = Singleton.instance()
    View Code

    支持多线程

    import time
    import threading
    class Singleton(object):
        _instance_lock = threading.Lock()
    
        def __init__(self):
            time.sleep(1)
    
        @classmethod
        def instance(cls, *args, **kwargs):
            if not hasattr(Singleton, "_instance"):
                with Singleton._instance_lock:
                    if not hasattr(Singleton, "_instance"):
                        Singleton._instance = Singleton(*args, **kwargs)
            return Singleton._instance
    
    
    # 第一次调用
    def task(arg):
        obj = Singleton.instance()
        print(obj)
    for i in range(10):
        t = threading.Thread(target=task,args=[i,])
        t.start()
    
    
    # 第二次调用    
    time.sleep(20)
    obj = Singleton.instance()
    View Code

    3.使用__new__(最常用)

    无法支持多线程

    class Singleton(object):
        
        Singleton._instance = None
    
        def __init__(self):
            pass
    
    
        def __new__(cls, *args, **kwargs):
            if not hasattr(Singleton, "_instance"):
                Singleton._instance = object.__new__(cls, *args, **kwargs)
            return Singleton._instance
    View Code

    支持多线程

    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"):
                        Singleton._instance = object.__new__(cls, *args, **kwargs)
            return Singleton._instance
    View Code

    4.基于metaclass

    -------------------------------(一)-------------------------------
    
    # 创建对象
    
    class SingletonType(type):
    
        def __call__(cls, *args, **kwargs):
            obj = super(SingletonType,cls).__call__(*args, **kwargs)   #type类帮创建__new__和__init__并返回
            return obj
    
    class Foo(metaclass=SingletonType):
        def __init__(self,name):
            self.name = name
    
    obj = Foo("alex")
    
    -------------------------------(二)-------------------------------
    
    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)
    

      

    有一种能力,是持续不断的努力
  • 相关阅读:
    省选模拟47 题解
    省选模拟46 题解
    死磕 java集合之PriorityQueue源码分析
    拜托,面试别再问我堆(排序)了!
    死磕 java集合之ConcurrentSkipListSet源码分析——Set大汇总
    死磕 java集合之CopyOnWriteArraySet源码分析——内含巧妙设计
    死磕 java集合之TreeSet源码分析
    死磕 java集合之LinkedHashSet源码分析
    死磕 java集合之HashSet源码分析
    死磕 java集合之ConcurrentSkipListMap源码分析——发现个bug
  • 原文地址:https://www.cnblogs.com/shaojiafeng/p/8253971.html
Copyright © 2011-2022 走看看