C# 单例模式

 

加同步锁前后两次判断实例是否已存在(可行,但不推荐)

    public sealed class Singleton3
    {
        private Singleton3()
        {
        }

        private static object syncObj = new object();

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

                return instance;
            }
        }
    }

 

静态构造函数创建,若程序中一直需要此实例,采用此最好;调用Instance方法时获取静态的instance,静态instance在class的静态构造方法运行时进行初始化,只运行一次,从而避免了多线竞争资源导致可能导致的重复实例化。

    public sealed class Singleton4
    {
        private Singleton4()
        {
        }

        private static Singleton4 instance = new Singleton4();
        public static Singleton4 Instance
        {
            get
            {
                return instance;
            }
        }
    }

上述写成如下更易理解,MSDN的静态构造函数供参考参考链接

    public sealed class Singleton4
    {
        private static Singleton4 instance;
        static Singleton4(){
           instance=new Singleton4();
         }
        private Singleton4()
        {
        }
        public static Singleton4 Instance
        {
            get
            {
                return instance;
            }
        }
    }

 

 

 

 

按需创建,相对于静态函数的直接构造,此需要调用Nested时,才进行实例化,故推荐。

    public sealed class Singleton5
    {
        Singleton5()
        {
        }

        public static Singleton5 Instance
        {
            get
            {
                return Nested.instance;
            }
        }
        class Nested
        {
            static Nested()
            {
            }

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

 

以上摘录于《剑指offer》

 

 

泛型的单位模式(下述为通过两次判断来实现,当然可以使用推荐方式),使用时通过继承的方式,然后获取子类的Instance即可。只是这有一个问题,你仍然能通过构造函数来构造实例,这就是一个麻烦的事情……

public class SingletonManager<T> where T : class, new()
{
    private static T instance;
    private static readonly object lockObject = new object();

    protected SingletonManager()
    {
        // 私有构造函数,防止外部实例化
    }

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

 

posted @ 2022-11-02 09:11  盛沧海  阅读(32)  评论(0编辑  收藏  举报