单件模式 The Singleton Pattern

单件模式——确保一个类只有一个实例,并提供一个全局访问点。(摘自《Head First Design Patterns》)
单件模式比较简单,下面给出个一个单件类:
public class Singleton

    {

        #region = Instance =



        private static Singleton _instance;



        public static Singleton Instance

        {

            get {

                if (_instance == null)

                {

                    _instance = new Singleton();

                }

                return _instance; }

        }



        #endregion





        private Singleton() { }

    }
该类不能实例化,只能通过Instance访问,任何时候都是访这一个实例,确保了全局唯一。,由于在后天实例化唯一实例,可能在多线程下会有差错,可以在单件里直接实例:
public class Singleton2

    {

        #region = Instance =



        private static Singleton2 _instance = new Singleton2();



        public static Singleton2 Instance

        {

            get { return _instance; }

        }



        #endregion





        private Singleton2() { }

    }
也可以进行同步:
public class SingletonForThreads

    {

        private volatile static SingletonForThreads _instance;

        public static SingletonForThreads Instance

        {

            get {

                if (_instance == null)

                {

                    lock (SingletonForThreads._instance)

                    {

                        if (_instance == null)

                        {

                            _instance = new SingletonForThreads();

                        }

                    }

                }

                return _instance;

            }

        }



        private SingletonForThreads() { }

    }
给出简单的三个小例子以供参考。
阅读更多

没有更多推荐了,返回首页