C#单例模式

前言:单例模式是我们在软件开发中比较常用的模式之一,能很好的理解并运用对软件的性能是有很大的帮助的。

一、饿汉式

public class Singleton

{

          private static Singleton _instance = new Singleton();

          private Singleton() { }

          public static Singleton GetInstance() { return _instance; }

}
View Code

点评:该种实现,在程序一运行就将对象加载到内存,由于静态变量是常驻于内存不会被GC回收,故该实例化方式适用于经常使用的对象。对象一开始就被实例化了所以在多线程环境下是线程安全的。

 

二、懒汉式

    //懒汉式(不安全)
    public class LazySingleton
    {
        private static LazySingleton instance = null;
        private LazySingleton()
        { }
        public static LazySingleton GetInstance()
        {
            if (instance == null)
                instance = new LazySingleton();
            return instance;
        }
    }
View Code

点评:在初次调用实例方法时才会创建实例,解决了饿汉式的缺点,但在多线程环境下是不安全的

 

三、懒汉式-线程安全

    //懒汉式(线程安全)
    public class LazySaleSingleton
    {
        private static object lockObj = new object();
        private static LazySaleSingleton instance = null;
        private LazySaleSingleton()
        { }
        public static LazySaleSingleton GetInstance()
        {
            lock (lockObj)
            {
                if (instance == null)
                    instance = new LazySaleSingleton();
            }
            return instance;
        }
    }
View Code

点评:解决了普通懒汉式的线程安全问题,但由于用到了锁,不管实例是否已存在都要执行锁区域的代码,带来了额外开销在高并发环境下不是最优方案

 

四、双验锁

 

    public class Singleton
    {
        private static object obj = new object();
        private static Singleton _singletion;
        private Singleton()
        { }

        public static Singleton Instance
        {
            get
            {
                if (_singletion == null)
                {
                    lock (obj)
                    {
                        if (_singletion == null)
                        {
                            _singletion = new Singleton();
                        }
                    }
                }
                return _singletion;
            }
        }
    }
View Code

点评:双验锁,相对于单检查锁,减少了不必要的入锁开销,可根据项目实际情况做出选择

 

五、静态内部类方式

    //静态内部类
    public class InterSingleton
    {
        private InterSingleton()
        { }
        public static class InterSingletonHelp
        {
            private static InterSingleton instance = new InterSingleton();
            public static InterSingleton GetInstance()
            {
                return instance;
            }
        }
    }
View Code

点评:无锁化,只有在真正使用单例对象时才会产生实例,线程安全

 

六、.net4.0  Lazy 模式

    //.net4.0 Lazy模式
    public class Singleton
    {
        private static Lazy<Singleton> instance = new Lazy<Singleton>();
        private Singleton()
        { }
        public static Lazy<Singleton> GetInstance()
        {
            return instance;
        }
    }
View Code

点评:对象延迟加载,当成员被访问时才初始化成员对象,提高了资源利用效率

 

posted @ 2018-06-30 22:35  <渔人>  阅读(304)  评论(0编辑  收藏  举报