码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-04-30 22:13:35      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

经典模式

 public class Singleton
    {
        private static Singleton instance;

        private Singleton()
        {

        }

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

Lazy模式

   public class Singleton
    {
        private static Singleton instance;
        private static object _lock = new object();

        private Singleton()
        {

        }

        public static Singleton GetInstance()
        {
            if (instance == null)
            {
                lock (_lock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

恶汉模式

  public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();

        private Singleton()
        {
        }

        public static Singleton GetInstance()
        {
            return instance;
        }
    }

 

单例模式

标签:

原文地址:http://www.cnblogs.com/badboys/p/5449519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!