单件模式

单件模式概念:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

我之前的概念搞混了,以为只要一个实例就是单件模式。它最主要的是提供一个访问它的全局访问点,也就是多次访问,一个类的实例地址。

代码如下:

using System;

namespace GlobalSpooler
{
    /// <summary>
    /// Summary description for Spooler.
    /// </summary>
    public class Spooler     {
        private static Spooler MySpooler ;
        private static bool instance_flag= false;
        private Spooler()  {
            instance_flag = true;
        }
        public static Spooler getSpooler() {
            if (! instance_flag) 
                MySpooler = new Spooler ();
             return MySpooler;
        }

    }
}

Main访问代码

using System;

namespace GlobalSpooler
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class GlobSpooler
    {
        static void Main(string[] args)
        {
            Spooler sp1 = Spooler.getSpooler();
            if (sp1 != null)
                Console.WriteLine("Got 1 spooler");
            Spooler sp2 = Spooler.getSpooler();
            if (sp2 == null)
                Console.WriteLine("Can\'t get spooler");

           if (sp1==sp2)
             Console.WriteLine ("They are same.");
          else
            Console.WriteLine ("They are not same.");

            //fails at compile time
            //Spooler sp3 = new Spooler();
        }
    }
}

 

 

 

你可能感兴趣的:(模式)