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

    单例模式

    单例模式是23种设计模式中比较简单的一类,整个过程中只有一个实例,所有生成的实例都指向同一块内存空间。

    实现单例的四种方法

    方法一

    通过类的绑定方法

    class Student:
        info = None
        
        def __init__(self, name, age):
            self.name = name
            self.age = age
            
        @classmethod
        def get_info(cls):
            if not cls.info:
                cls.info = cls('wu', 18)
            return cls.info
    
    s1 = Student.get_info()
    s2 = Student.get_info()
    s3 = Student('xiaowu', 19)
    print(s1)
    print(s2)
    print(s3)
    

    方法二

    通过装饰器

    def get_info(cls):
        info = cls('wu', 18)
        
        def inner(*args, **kwargs):
            if len(args) != 0 or len(kwargs) != 0:
                res = cls(*args, **kwargs)
                return res
            else:
                return info
    	return inner
    
    @get_info
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    s1 = Student()
    s2 = Student()
    s3 = Student('xiaowu', 19)
    print(s1)
    print(s2)
    print(s3)
    

    方法三

    通过元类

    class Mymeta(type):
        def __init__(self, name ,bases, dic):
            self.info = self('wu', 18)
        def __call__(self, *args, **kwargs):
            if len(args) != 0 or len(kwargs) != 0:
                obj = object.__new__(self)
                obj.__init__(*args, **kwargs)
                return obj
            else:
                return self.info
    
    class Student(metaclass=Mymeta):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    s1 = Student()
    s2 = Student()
    s3 = Student('xiaowu', 19)
    print(s1)
    print(s2)
    print(s3)
    

    方法四

    通过模块导入。在python中,模块是天然的单例

    # student.py(模块文件)
    
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    s1 = Student('wu', 18)
    
    def test():
        from student import s1
        print(s1)
    
    test()
    from student import s1
    from student import Student
    s2 = Student('xiaowu', 19)
    print(s1)
    print(s2)
    

    单例模式的优点

    1. 由于单例模式要求在全局只有一个实例,因而可以节省比较多的内存空间。
    2. 全局只有一个接入点,可以更好地进行数据同步控制,避免多重占用。
    3. 单例可长驻内存,减少系统开销。

    单例模式的缺点

    1. 单例模式的扩展是比较困难的。
    2. 赋予了单例以太多的职责,某种程度上违反了单一职责原则。
    3. 单例模式是并发协作软件模块中需要最先完成的,因而其不利于测试。
    4. 单例模式在某种情况下会导致“资源瓶颈”。
  • 相关阅读:
    一些博客
    【iOS】得到当前年、月、周的第一天和最后一天
    iOS学习路线
    UI开发--响应者链条
    通知中心 NSNotificationCenter
    UITableView的编辑(插入、删除、移动)
    FMDatabaseQueue 如何保证线程安全
    理解 dispatch_get_specific
    instancetype
    【转】手把手教你ARC——iOS/Mac开发ARC入门和使用
  • 原文地址:https://www.cnblogs.com/yunluo/p/11459872.html
Copyright © 2011-2022 走看看