C#学习 - 关于懒汉式和饿汉式单例

1. Eager Singleton(饿汉式单例类),其静态成员在类加载时就被初始化,此时类的私有构造函数被调用,单例类的唯一实例就被创建。

        class EagerSingleton
        {
            private static EagerSingleton instance = new EagerSingleton();

            private EagerSingleton() { }

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

2. Lazy Singleton(懒汉式单例类),其类的唯一实例在真正调用时才被创建,而不是类加载时就被创建。所以Lazy Singleton不是线程安全的。

        class LazySingleton
        {
            private LazySingleton() { }

            private static LazySingleton instance = null;

            public static LazySingleton GetInstance()
            {
                if (instance == null)
                    instance = new LazySingleton();
                return instance;
            }
        }
注意:不管是懒汉还是饿汉,其构造函数必须私有,以防多个实例被创建。另外,用懒汉式单例在多线程环境中需要其他的保护措施来保证只有单例被创建,因为可能有多个线程同时调用GetInstance()。

猜你喜欢

转载自blog.csdn.net/jianhui_wang/article/details/80774440