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

时间:2021-07-21
本文章向大家介绍2.C#设计模式系列01_单例模式_Singleton,主要包括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<SingletonThree> lazyModel = new Lazy<SingletonThree>(() => new SingletonThree());
        private SingletonThree(){
        }

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

        private static Lazy<SingletonFour> lazyModel;
        private SingletonFour(){
        }

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

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

总结:

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

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

本文来自博客园,作者:碧水孤鹜,转载请注明原文链接:https://www.cnblogs.com/wandefour/p/15038587.html,请各位大佬多多教诲

原文地址:https://www.cnblogs.com/wandefour/p/15038587.html