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

    单例模式 (singleton),保证一个类仅有一个实例,并提供个访问它的全局访问点。

    Singleton pattern provides a mechanism to limit the number of the instances of the class to one. Thus the same object is always shared by different parts of the code. Singleton can be seen as a more elegant solution to global variable because actual data is hidden behind Singleton class interface.
    在面向对象代码中, 使用全局函数是比较丑陋的代码, 单例模式可用作为它比较好的替代方案, 该模式提供单点访问机制, 在代码始终都访问到同一个对象.

    image

    class Singleton
    {
        private static Singleton instance; //类变量,对于该类的所有对象共享
        
        private Singleton() {} //私有化构造函数, 客户不能直接生成类对象
        
        public static Singleton GetInstance() //类函数,无需对象,可用类直接调用
        {
            if (instance == null) //只会生成一个对象
            {
                instance = new Singleton();
            }
            return instance;
        }
    }

    客户代码,

    Singleton s = Singleton.GetInstance(); 

    对于多线程的singleton, 需要加锁,

    class Singleton
    {
        private static Singleton instance; 
        private static object syncRoot = new object() //加锁的对象,此时instance对象还没有创建成功,需要一个对象用于加锁
        
        private Singleton() {} 
        
        public static Singleton GetInstance() 
        {
            if (instance == null) //双重锁定, 只有当无instance时才加锁, 提高效率
            {
                lock(syncRoot) //加锁,只有一个线程可以创建对象
                 {
                    if (instance == null) 
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    
     

    Python has no private constructors we have to find some other way to prevent instantiations.
    对于python, singleton模式的实现比较特别, 必须要有个办法在init函数里面阻止其初始化, 这儿采用的办法是抛异常…

    class Singleton:
        __single = None
        def __init__( self ):
            if Singleton.__single:
                raise Singleton.__single
            Singleton.__single = self
    
    def Handle():
        try:
            single = Singleton()
        except Singleton, s:
            single = s
        return single    
  • 相关阅读:
    Java内部类
    sql几种连接的区别
    常见的十大算法
    使用yml文件配置数据库数据时的问题
    SpringBoot整合Mybatis
    不是书评 :《我是一只IT小小鸟》
    考试考完了·
    MSSQL站库分离情况的渗透思路
    VENOM cve-2015-3456 Qemu 虚拟机逃逸漏洞POC
    Python 实现指定目录下 删除指定大小的文件
  • 原文地址:https://www.cnblogs.com/fxjwind/p/2916113.html
Copyright © 2011-2022 走看看