c# 单例及静态类笔记

    //单例应该是一个sealed类,不能被继承
    //单例并不是线程安全的,在多线程情况下,有可能产生第二个实例
    //单例的线程安全版本应该使用"双锁定"技术
    //静态类非实例对象,静态类违反面向对象的三大特性中的两项:继承和多态
    //静态类无法从其它类型继承
    //静态类不能作为参数,也不能作为返回值
    public class TestClass {
        public static void TestMethod() {
            Singleton.Instance.SampleMethod();
            ThreadSafetySingleton.Instance.SampleMethod();
        }
    }

    public sealed class Singleton {
        private static Singleton instance = null;

        private Singleton() { }//防止被new出来

        public static Singleton Instance {
            get { return instance == null ? new Singleton() : instance; }
        }

        public void SampleMethod() {

        }
    }

    public sealed class ThreadSafetySingleton {
        static ThreadSafetySingleton instance = null;//默认private
        static readonly object padLock = new object();//默认private

        ThreadSafetySingleton() { }//默认private,防止被new出来

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

        public void SampleMethod() {

        }
    }

参考文献:

 《编写高质量代码改善C#程序的157个建议》

posted @ 2021-08-05 14:27  狼王爷  阅读(73)  评论(0编辑  收藏  举报