Singleton Pattern (5)

单件模式:

         确保一个类只能创建一个实例,在全局中只有唯一的访问点。

示例代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Security.Cryptography;

 

namespace Hello

{

   class Singleton

   {

      private int number = 0;

      private static Singleton uniqueInstance;

      private Singleton()

      {

     

      }

      public static Singleton GetInstance()

      {

        if (uniqueInstance == null)

        {

           uniqueInstance = new Singleton();

        }

        return uniqueInstance;

      }

      public void SetNumber(int para)

      {

        number = para;

      }

      public void PrintNumber()

      {

        Console.WriteLine(number);

      }

   }

 

   class Program

   {

      static void Main(string[] args)

      {

        Singleton singleton1 = Singleton.GetInstance();

        singleton1.SetNumber(10);

        singleton1.PrintNumber();

 

        Singleton singleton2 = Singleton.GetInstance();

        singleton2.SetNumber(20);

        singleton2.PrintNumber();

 

        singleton1.PrintNumber();

      }

   }

}

 

posted @ 2011-09-30 09:11  Erebus_NET  阅读(103)  评论(0编辑  收藏  举报