四.享元模式实例分析(Example)
1、场景
一个文档Document中只有少数字符需要共享。结构如下图所示
CharacterFactory类,享元工厂,用来创建和管理Charactor对象。如果请求的Charactor对象存在,怎返回已经存在的对象。否则新创建一个新的对象返回。
Character类:享元抽象类,通过这个接口,Character可以接受并作用与外部状态。
CharacterA /CharacterB/CharacterC 类:实现享元抽象类,为内部状态添加存储空间。
CharacterA /CharacterB/CharacterC 类:实现享元抽象类,为内部状态添加存储空间。
2、代码
1、字符工厂类CharacterFactory
|
class CharacterFactory
{
private Dictionary<char, Character> _characters = new Dictionary<char, Character>();
public Character GetCharacter(char key)
{
// Uses "lazy initialization"
Character character = null;
if (_characters.ContainsKey(key))
{
character = _characters[key];
}
else
{
switch (key)
{
case 'A': character = new CharacterA(); break;
case 'B': character = new CharacterB(); break;
//...
case 'Z': character = new CharacterZ(); break;
}
_characters.Add(key, character);
}
return character;
}
}
|
2、抽象数据对象类DataObject及其具体实现类CustomersData
|
/// <summary>
/// The 'Flyweight' abstract class
/// </summary>
abstract class Character
{
protected char symbol;
protected int width;
protected int height;
protected int ascent;
protected int descent;
protected int pointSize;
public abstract void Display(int pointSize);
}
/// <summary>
/// A 'ConcreteFlyweight' class
/// </summary>
class CharacterA : Character
{
public CharacterA()
{
this.symbol = 'A';
this.height = 100;
this.width = 120;
this.ascent = 70;
this.descent = 0;
}
public override void Display(int pointSize)
{
this.pointSize = pointSize;
Console.WriteLine(this.symbol + " (pointsize " + this.pointSize + ")");
}
}
/// <summary>
/// A 'ConcreteFlyweight' class
/// </summary>
class CharacterB : Character
{
public CharacterB()
{
this.symbol = 'B';
this.height = 100;
this.width = 140;
this.ascent = 72;
this.descent = 0;
}
public override void Display(int pointSize)
{
this.pointSize = pointSize;
Console.WriteLine(this.symbol + " (pointsize " + this.pointSize + ")");
}
}
// ... C, D, E, etc.
/// <summary>
/// A 'ConcreteFlyweight' class
/// </summary>
class CharacterZ : Character
{
// Constructor
public CharacterZ()
{
this.symbol = 'Z';
this.height = 100;
this.width = 100;
this.ascent = 68;
this.descent = 0;
}
public override void Display(int pointSize)
{
this.pointSize = pointSize;
Console.WriteLine(this.symbol +" (pointsize " + this.pointSize + ")");
}
}
|
3、客户端代码
|
static void Main(string[] args)
{
// Build a document with text
string document = "AAZZBBZB";
char[] chars = document.ToCharArray();
CharacterFactory factory = new CharacterFactory();
// extrinsic state
int pointSize = 10;
// For each character use a flyweight object
foreach (char c in chars)
{
pointSize++;
Character character = factory.GetCharacter(c);
character.Display(pointSize);
}
Console.ReadKey();
}
|
3、实例运行结果
五、总结(Summary)
本文对享元模式(Flyweight Pattern)的概念、设计结构图、代码、使用场景、进行了描述。以一个享元模式实例进行了说明。如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销,这时可以考虑使用享元模式。
本文转自 灵动生活 51CTO博客,原文链接:http://blog.51cto.com/smartlife/269010,如需转载请自行联系原作者