设计模式(C#)之享元模式(Flyweight Pattern)
代码下载
1.概念
运用共享技术有效地支持大量细粒度的对象。
2.类图
Model.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlyweightPattern
{
public class Model
{
public double D1
{
get;
set;
}
public double D2
{
get;
set;
}
}
}
AbstractSum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlyweightPattern
{
public abstract class AbstractSum
{
public abstract double Sum(Model md);
}
}
Sum1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlyweightPattern
{
public class Sum1 : AbstractSum
{
public override double Sum(Model md)
{
return md.D1 + md.D2;
}
}
}
Sum2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlyweightPattern
{
public class Sum2 : AbstractSum
{
public override double Sum(Model md)
{
return md.D1 * md.D2;
}
}
}
FlyweightUse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlyweightPattern
{
public class FlyweightUse
{
private Dictionary<string, AbstractSum> _sumObjects = new Dictionary<string, AbstractSum>();
public AbstractSum GetSumObject(string key)
{
AbstractSum SumObject = null;
if (_sumObjects.ContainsKey(key))
{
SumObject = _sumObjects[key];
}
else
{
switch (key)
{
case "Sum1": SumObject = new Sum1(); break;
case "Sum2": SumObject = new Sum2(); break;
}
_sumObjects.Add(key, SumObject);
}
return SumObject;
}
}
}
3.调用
代码下载