单例模式

最近重读设计模式,理解更上一层楼。

为以便日后翻阅之需特坚持写博客,记录技术点滴,本设计模式系列源码均参考 http://c.biancheng.net/view/1317.html java语言版本的23种设计模式,同时方便没有java基础的同学参阅故翻译成C#系列。

 

 /// <summary>
    /// 延迟单例
    /// </summary>
    public class LazySingleton
    {
        private static volatile LazySingleton instance = null;
        private LazySingleton() { }  //避免类在外部被实例化
        private static object obj = new object();
        public static LazySingleton GetInstance()
        {
            lock (obj)
            {
                if (instance == null)
                {
                    instance = new LazySingleton();
                }
            }

            return instance;
        }

    }

    /// <summary>
    /// 饿汉单例模式
    /// </summary>
    public class HungrySingleton
    {
        private static readonly HungrySingleton instance = new HungrySingleton();
        private HungrySingleton() {  }
        public static HungrySingleton GetInstace()
        {
            return instance;
        }
    }

 

posted on 2019-08-03 12:46  迎着风追赶  阅读(99)  评论(0)    收藏  举报

导航