美文网首页
单例模式 Singleton

单例模式 Singleton

作者: 逢春枯木 | 来源:发表于2019-07-10 23:24 被阅读0次

单例模式 Singleton

定义

  • 一个类有且只有一个实例,并提供一个访问该实例的全局访问点,实现共享资源的访问控制

适用场景

当一个对象的生产需要比较多的资源时,如读取配置,产生其他依赖对象时,可以通过在应用启动时,直接产生一个单例对象,然后永久驻留内存的方式解决。

  • 生成全局唯一变量(UUID)
  • 访问全局复用的唯一资源(总线,磁盘)、系统全局统一管理(任务管理器)、操作系统中的文件系统
  • 应用程序中的日志应用,配置文件读取器
  • 网站应用中的计数器、数据库连接池

优缺点

  • 优点:

    • 只有一个实例,所以可以节省内存空间,实例可以永驻内存空间,减少系统资源开销
    • 全局只有一个访问点,有利于更好的进行数据同步控制,避免多重占用
  • 缺点:

    • 单例违反了开闭原则,对于扩展比较麻烦
    • 单例违反了职责单一原则,被赋予了太多的职责,无法将对象的定义和创建隔离开来
    • 单例在并发协作项目中需要最先完成,不利于测试
    • 使用单例太多,可能导致资源瓶颈

Python实现

  • 饿汉式单例模式(线程安全,效率高,但是无法延时加载)

    
    #!/usr/bin/env python3
    # -*- coding=utf-8 -*-
    
    
    class SingletonDemo1:
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls, 'instance'):
                cls.instance = super().__new__()
            return cls.instance
      
    s = SingletonDemo1()
    print("Object created", s)
      
    s1 = SingletonDemo1()
    print("Ohject created", s)
        
    
    • 结果:
    
    /home/tiven/python/designpatterns/venv/bin/python /home/tiven/python/designpatterns/src/creationalpatterns/singleton/singletonDemo1.py
    Object created <__main__.SingletonDemo1 object at 0x7f392eb5b9e8>
    Object created <__main__.SingletonDemo1 object at 0x7f392eb5b9e8>
    
    Process finished with exit code 0
    
    
  • 懒汉式单例模式(线程安全,效率低,可以延时加载)

    
    #!/usr/bin/env python3
    # -*- coding=utf-8 -*-
    
    
    class SingletonDemo2:
    
        instance = None
    
        def __init__(self):
            if SingletonDemo2.instance:
                print("Instance already created:")
                self.getInstance()
            else:
                print("__init__ method called...")
    
        @classmethod
        def getInstance(cls):
            if not cls.instance:
                cls.instance = SingletonDemo2()
            return cls.instance
    
    
    if __name__ == '__main__':
        s1 = SingletonDemo2()
        s1.getInstance()
        print("Object created", s1.getInstance())
        print("Object created", s1)
        s2 = SingletonDemo2()
        s2.getInstance()
        print("Object created", s2.getInstance())
        print("Object created", s2)
    
    
    • 结果:
    
    /home/tiven/python/designpatterns/venv/bin/python /home/tiven/python/designpatterns/src/creationalpatterns/singleton/singletonDemo2.py
    __init__ method called...
    __init__ method called...
    Object created <__main__.SingletonDemo2 object at 0x7f81155c9c50>
    Object created <__main__.SingletonDemo2 object at 0x7f81155c9c18>
    Instance already created:
    Object created <__main__.SingletonDemo2 object at 0x7f81155c9c50>
    Object created <__main__.SingletonDemo2 object at 0x7f81155c9cf8>
    
    Process finished with exit code 0
    
    

相关文章

网友评论

      本文标题:单例模式 Singleton

      本文链接:https://www.haomeiwen.com/subject/djllkctx.html