享元模式

一、享元模式是为了解决一个系统创建了过多类实例而带来的系统开销的解决方案

二、内部状态,即在一个对象中不会随外部环境不同而发生变化的状态,是需要被共享的状态

三、外部状态,与内部状态相反

四、以下是一个公司饮水机的例子。使用享元模式,保存了各个部门的饮水机实例,不需要在每个员工饮水的时候去实例化。

    

View Code
/// <summary>
/// 饮水机超类
/// </summary>
public abstract class WaterMachine
{
/// <summary>
/// 剩余的水量
/// </summary>
public int WaterCount
{
get;
protected set;
}

/// <summary>
/// 员工饮水
/// </summary>
/// <param name="count"></param>
public abstract void DrinkWater(int count);

/// <summary>
/// 设置饮水机水量
/// </summary>
/// <returns></returns>
protected abstract int GetWaterCount();


public WaterMachine() {
this.WaterCount = this.GetWaterCount();
}
}
/// <summary>
/// 员工用饮水机
/// </summary>
public class EmployeeWaterMachine:WaterMachine
{

public override void DrinkWater(int count)
{
if (this.WaterCount == 0) {
Console.WriteLine(
"没水了!"); return;
}
this.WaterCount = this.WaterCount - count;
if (this.WaterCount < 0) {
Console.WriteLine(
"没这么多水,先给你一点!"); this.WaterCount = 0; return;
}
Console.WriteLine(
"倒水成功了!"); return;
}

protected override int GetWaterCount()
{
return 100;
}
}



View Code
/// <summary>
/// 享元工厂,保存了每个部门的饮水机实例
/// </summary>
public class ShareFactory
{
private Dictionary<string, WaterMachine> machines = new Dictionary<string, WaterMachine>();

/// <summary>
/// 通过部门名称获得饮水机
/// </summary>
/// <param name="postName"></param>
/// <returns></returns>
public WaterMachine GetWaterMachine(string postName) {
if (!this.machines.ContainsKey(postName)) {
this.machines.Add(postName, new EmployeeWaterMachine());
}
return this.machines[postName];
}
}
View Code
/// <summary>
/// 客户端调用
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
ShareFactory factory
= new ShareFactory();

WaterMachine machine1
= factory.GetWaterMachine("研发部");
machine1.DrinkWater(
50);
WaterMachine machine2
= factory.GetWaterMachine("研发部");
machine1.DrinkWater(
60);
WaterMachine machine3
= factory.GetWaterMachine("研发部");
machine1.DrinkWater(
50);

WaterMachine machine4
= factory.GetWaterMachine("人资部");
machine4.DrinkWater(
50);

Console.ReadKey();
}
posted @ 2011-05-18 11:56  CNF  阅读(240)  评论(0编辑  收藏  举报