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    
  • 相关阅读:
    正则表达式的妙用获得数组
    道不远人,话IO框架
    页面和控件的生命周期及其二者的关系
    深度解析 TypeConverter & TypeConverterAttribute (二)
    今天我顺利的在cnblogs安家,我要在这里写下辉煌
    AJAX or Ajax
    深度解析 TypeConverter & TypeConverterAttribute (一)
    SonarQube简单入门
    vuecli · Failed to download repo vuejstemplates/webpack: connect ETIMEDOUT 192.30.253.112:443
    Sqlmap使用教程
  • 原文地址:https://www.cnblogs.com/fxjwind/p/2916113.html
Copyright © 2011-2022 走看看