您的位置:首页 > 其它

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

2008-03-05 13:16 218 查看
单件模式


整个系统中对象是唯一的

也可以有固定数目个
如:对象池、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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: