星辉

星月同辉 e路随行
.net/vs2005/c#/web/ajax
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

NET常用设计模式——单件模式

Posted on 2007-12-23 12:48  star163  阅读(367)  评论(0)    收藏  举报

单件模式

  • 整个系统中对象是唯一的
  • 也可以有固定数目个
    如:对象池、portal中的配置对象 当前httpcontext appdomain

应用实列(一)

using System;
namespace CSDesingPattern
{
    
class Singleton
    {
        
private static Singleton mInstance;
        
private int x = 0;

        
//私有构造函数
        private Singleton() { }

       
//实现单件实例
        public static Singleton GetObject()
        {
            
if (mInstance == null)
                mInstance 
= new Singleton();
            
return mInstance;
        }

        
public void SetX(int newVal)
        {
            x 
= newVal;
        }

        
public int GetX()
        {
            
return x;
        }

        
static void Main(string[] args)
        {

            
int val;
            Singleton s1 
= Singleton.GetObject();
            Singleton s2 
= Singleton.GetObject();
            Console.WriteLine(
"将Singleton对象中的X设置为10");
            s1.SetX(
10);
            val 
= s2.GetX();
            Console.WriteLine(
"使用第二个Singleton变量读取X的值 x={0}", val);
        }
    }
}