设计模式:Singleton(结构型)

Singleton模式目的:保证一个类只有一个实例,并提供一个访问它的全局访问点.

Singleton适用:
1.当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时.
2.当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

Demo:
 

class Singleton 
{
   
//静态存储对象,保证全局唯一
   private static Singleton _instance;
   
   
//制作一个实例化本对象的方法,它方通过调用这个方
   
//法取得对象
   public static Singleton Instance()
   
{
     
if (_instance == null)
    _instance 
= new Singleton();
    
return _instance;
   }

  
////构造函数发布为私有,不能够使用构造函数取得对象
   private Singleton(){}

  
   
private int x = 0;
   
public void SetX(int newVal){x = newVal;}
   
public int GetX(){return x;}        
}

Singleton使用:
public class Client
{
  
public static void Main(string[] args)
  
{            
    
int val;            
   Singleton firstSingleton 
= Singleton.Instance(); 
   Singleton secondSingleton 
= Singleton.Instance();

   firstSingleton.SetX(
4);
   Console.WriteLine(
"Using first variable for singleton, set x to 4");
   val 
= secondSingleton.GetX();
   Console.WriteLine(
"Using second variable for singleton, value retrieved = {0}", val);        
            
        }

    }
posted @ 2007-08-30 10:24  南山放牛  阅读(81)  评论(0)    收藏  举报