2.C#设计模式系列01_单例模式_Singleton


前言:单例模式个人觉得是比较容易理解,而且面试比较容易遇到,但是在实际生产中要慎用的一种设计模式,以前总觉得很难,系统的了解了下,主要有以下几种写法

1.双if + lock 

 1 public class SingletonModel {
 2 
 3         private static SingletonModel instance = null;
 4         private static object singleton_lock = new object();
 5         private SingletonModel() {
 6             Console.WriteLine("构造函数");
 7         }
 8 
 9         //多线程测试
10         public static SingletonModel SingletonCreatInstance() {
11             if (instance == null){
12                 lock (singleton_lock){
13                     if (instance == null){
14                         instance = new SingletonModel();
15                     }
16                 }
17             }
18             return instance;
19         }
20     }

2.静态成员变量

  public class SingletonTwo{

        private static SingletonTwo slModel = new SingletonTwo();
        private SingletonTwo() {
            Console.WriteLine("构造函数");
        }

        public static SingletonTwo CreateInstanceTwo{
            get{
                return slModel;
            }
        }
    }

3.静态构造函数

public class SingletonOne {

        //静态构造函数
        private static SingletonOne slModel =null;
        static SingletonOne(){
            slModel = new SingletonOne();
            Console.WriteLine("构造函数");
        }

        public static  SingletonOne CreateInstance() {
            return slModel;
        }
    }

4.Lazy延时加载

public class SingletonThree {
        private static Lazy lazyModel = new Lazy(() => new SingletonThree());
        private SingletonThree(){
        }

        public static SingletonThree CreatInstance() {
            return lazyModel.Value;
        }
    }
public class SingletonFour{

        private static Lazy lazyModel;
        private SingletonFour(){
        }

        static SingletonFour() {
            lazyModel = new Lazy(new SingletonFour());
        }

        public static SingletonFour CreatInstance() {
            return lazyModel.Value;
        }
    }

总结:

套路无非就是  1.私有构造函数或者静态构造函数 + 2.私有静态成员变量  + 3.公共对外的访问实例方法 ,然后根据实际情况选择合适的用法

ps:Lazy 用法个人感觉使用静态成员变量和静态构造是一样的

Net