class1.cs

来自「来自DoFactory的设计模式, 由于是本人根据已有代码创建,没有NETOpt」· CS 代码 · 共 51 行

CS
51
字号
// Singleton pattern -- Structural example  

using System;

namespace DoFactory.GangOfFour.Singleton.Structural
{

    // MainApp test application 

    class MainApp
    {

        static void Main()
        {
            // Constructor is protected -- cannot use new 
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user 
            Console.Read();
        }
    }

    // "Singleton" 

    class Singleton
    {
        private static Singleton instance;

        // Note: Constructor is 'protected' 
        protected Singleton()
        {
        }

        public static Singleton Instance()
        {
            // Use 'Lazy initialization' 
            if (instance == null)
            {
                instance = new Singleton();
            }

            return instance;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?