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

单例模式的几种写法

时间:2015-08-11 20:49:10      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:

第一种:

    public sealed class Singleton1
    {
        private static Singleton1 instance;

        private Singleton1()
        {

        }

        public static Singleton1 Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Singleton1();
                }
                return instance;
            }
        }

    }

第二种:

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

        private Singleton2()
        {

        }

        public static Singleton2 Instance
        {
            get
            {
                return instance;
            }
        }
    }

 

第三种:

   public sealed class Singleton3
    {
        private static volatile Singleton3 instance = null;

        private static object syncRoot = new object();

        private Singleton3()
        {

        }

        public static Singleton3 Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton3();
                        }
                    }
                }
                return instance;
            }
        }
    }

 

第四种:

    public sealed class Singleton4
    {
        //因为下面声明了静态构造函数,所以在第一次访问该类之前,new Singleton4()语句不会执行
        private static readonly Singleton4 _instance = new Singleton4();
        static Singleton4()
        {

        }

        private Singleton4()
        {

        }

        public static Singleton4 Instance
        {
            get
            {
                return _instance;
            }
        }
    }

 

第五种:

    public sealed class Singleton5
    {
        private Singleton5()
        {

        }

        public static Singleton5 Instance { get { return Nested._instance; } }

        private class Nested
        {
            static Nested()
            {

            }

            internal static readonly Singleton5 _instance = new Singleton5();
        }
    }

 

第六种:

    public sealed class Singleton6
    {
        private static readonly Lazy<Singleton6> _instance = new Lazy<Singleton6>(() => new Singleton6());

        private Singleton6()
        {

        }

        public static Singleton6 Instance { get { return _instance.Value; } }
    }

 

第七种,先是一个抽象的单例类:

    /// <summary>
    /// 1.声明抽象类,以便不能直接使用,必须继承该类才能用
    /// 2.使用Lazy<T>作为_instance,T就是我们要实现单例的继承类
    /// 3.根据微软的文档和单例特性,单例类的构造函数必须是私有的,所以这里要加相应的验证
    /// 4.一旦验证通过,就invoke这个私有的无参构造函数
    /// 5.Instance属性返回唯一的一个T的实例
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class Singleton7<T>
    {
        private static readonly Lazy<T> _instance = new Lazy<T>
            (
            () =>
            {
                var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                if (ctors.Count() != 1)
                {
                    throw new InvalidOperationException(string.Format("Type {0} must have exactly one constructor.", typeof(T)));
                }
                var ctor = ctors.SingleOrDefault(c => c.GetParameters().Count() == 0 && c.IsPrivate);
                if (ctor == null)
                {
                    throw new InvalidOperationException(string.Format("The constructor for {0} must be private and take no parameters", typeof(T)));
                }
                return (T)ctor.Invoke(null);
            }
            );

        public static T Instance { get { return _instance.Value; } }
    }

 

继承上面抽象类的子类:

    class MySingleton : Singleton7<MySingleton>
    {
        int _counter;

        public int Counter { get { return _counter; } }

        private MySingleton()
        {
            _counter = 0;
        }

        public void IncrementCounter()
        {
            //++_counter;
            //线程安全
            Interlocked.Increment(ref _counter);
        }
        
    }

 

单例模式的几种写法

标签:

原文地址:http://www.cnblogs.com/laixiancai/p/4721675.html

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