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    
  • 相关阅读:
    SQL易错总结1
    线程池使用总结
    多线程的上下文切换
    SQL 排序按指定内容优先排序
    System x 服务器制作ServerGuide U盘安装Windows Server 2008 操作系统 --不格式化盘
    错误“该伙伴事务管理器已经禁止了它对远程/网络事务的支持”解决方案
    sql server 2012 链接服务器不能链接sql server 2000的解决方案 ,
    sqlserver2005版本的mdf文件,还没有log文件,
    BCP SQL导出EXCEL常见问题及解决方法;数据导出存储过程
    Nginx
  • 原文地址:https://www.cnblogs.com/fxjwind/p/2916113.html
Copyright © 2011-2022 走看看