设计模式---单例模式

单例模式:保证一个类仅有一个实例,并提供一个访问它的全局变量。

通常我们可以让一个全局变量使得一个对象被访问,但它不能防止你实例化多个对象。一个最好的方法就是让类自身负责保存它的唯一实例。这个类可以保证没有其他实例可以被创建,并且提供一个访问该实例的方法。

Singleton
-instance(私有变量)
-Singleton(私有构造函数)
+GetInstance(公有函数)

代码如下:

class Singleton{
    private static Singleton instance;
    private Singleton(){
    
    }
    public Singleton GetInstance(){
        if(instance == null)
            instance = new Singleton();
        return instance;
    }
}

在多线程程序中,多个线程同时访问Singleton类时,调用GetInstance方法,会有可能造成创建多个实例。

此时,就需要加上进程锁,保证当是个线程位于代码的临界区时,另一个线程不进入临界区,如果其他线程试图进入锁定的代码,则它将一直等待,直到该对象被释放。

class Singleton{
    private static Singleton instance;
    private static readonly object synRoot = new object();
    private Singleton(){
    
    }
    public Singleton GetInstance(){
        lock(synRoot){
            if(instance == null)
                instance = new Singleton();
        }
        return instance;
    }
}

每次访问GetInstance都需要加锁,会影响性能,改进的方法是双重锁定

class Singleton{
    private static Singleton instance;
    private static readonly object synRoot = new object();
    private Singleton(){
    
    }
    public Singleton GetInstance(){
        if(instance == null){
            lock(synRoot){
            if(instance == null)
                instance = new Singleton();
            }
        }
        return instance;
    }
}

只有在创建instance的时候,加上进程锁,并且防止了多个进程同时访问Getinstance时创建多个实例。

原文地址:https://www.cnblogs.com/sysu-kiros/p/3249074.html