关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回

(DesignPattern)Singleton.

发布时间:2022-07-27 13:55:17
Role:(DesignPattern)S
ingleton.

The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object.

Design:

  • Make the constructor private and add a private static constructor as well.
  • Add a private static read-only object that is internally instantialed using the private constructor.
  • Add a public static property that accesses the private object.

Implementation:

    public sealed class Singleton
    {
        // Private constructor.
        private Singleton()
        {
            Console.WriteLine("One instance is created."); 
        }

        // private object instantiated with private constructor.
        private static readonly Singleton instance = new Singleton(); 

        // Public static property to get the object.
        public static Singleton UniqueInstance
        {
            get
            {
                return instance; 
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s0 = Singleton.UniqueInstance;
            Singleton s1 = Singleton.UniqueInstance;
            Singleton s2 = Singleton.UniqueInstance; 
        }
    }

/template/Home/DawnNew/PC/Static

立即注册风纳云账号,免费体验多款产品

立即注册