结构型模式篇-享元模式(Flyweight Pattern)
按照这样的实现思路,可以发现如果有多个客户端程序使用的话,会出现大量的重复性的逻辑,用重构的术语来说是出现了代码的坏味道,不利于代码的复用和维护;另外把这些状态和行为移到客户程序里面破坏了封装性的原则。再次转变我们的实现思路,可以确定的是这些状态仍然属于Charactor对象,所以它还是应该出现在Charactor类中,对于不同的状态可以采取在客户程序中通过参数化的方式传入。类结构图如下:


// "Charactor"
public abstract class Charactor
{
//Fields
protected char _symbol;
![]()
protected int _width;
![]()
protected int _height;
![]()
protected int _ascent;
![]()
protected int _descent;
![]()
protected int _pointSize;
![]()
//Method
public abstract void SetPointSize(int size);
public abstract void Display();
}
![]()
// "CharactorA"
public class CharactorA : Charactor
{
// Constructor
public CharactorA()
{
this._symbol = 'A';
this._height = 100;
this._width = 120;
this._ascent = 70;
this._descent = 0;
}
![]()
//Method
public override void SetPointSize(int size)
{
this._pointSize = size;
}
![]()
public override void Display()
{
Console.WriteLine(this._symbol +
"pointsize:" + this._pointSize);
}
}
![]()
// "CharactorB"
public class CharactorB : Charactor
{
// Constructor
public CharactorB()
{
this._symbol = 'B';
this._height = 100;
this._width = 140;
this._ascent = 72;
this._descent = 0;
}
![]()
//Method
public override void SetPointSize(int size)
{
this._pointSize = size;
}
![]()
public override void Display()
{
Console.WriteLine(this._symbol +
"pointsize:" + this._pointSize);
}
}
![]()
// "CharactorC"
public class CharactorC : Charactor
{
// Constructor
public CharactorC()
{
this._symbol = 'C';
this._height = 100;
this._width = 160;
this._ascent = 74;
this._descent = 0;
}
![]()
//Method
public override void SetPointSize(int size)
{
this._pointSize = size;
}
![]()
public override void Display()
{
Console.WriteLine(this._symbol +
"pointsize:" + this._pointSize);
}
}
![]()
// "CharactorFactory"
public class CharactorFactory
{
// Fields
private Hashtable charactors = new Hashtable();
![]()
// Constructor
public CharactorFactory()
{
charactors.Add("A", new CharactorA());
charactors.Add("B", new CharactorB());
charactors.Add("C", new CharactorC());
}
![]()
// Method
public Charactor GetCharactor(string key)
{
Charactor charactor = charactors[key] as Charactor;
![]()
if (charactor == null)
{
switch (key)
{
case "A": charactor = new CharactorA(); break;
case "B": charactor = new CharactorB(); break;
case "C": charactor = new CharactorC(); break;
//
}
charactors.Add(key, charactor);
}
return charactor;
}
}
![]()
public class Program
{
public static void Main()
{
CharactorFactory factory = new CharactorFactory();
![]()
// Charactor "A"
CharactorA ca = (CharactorA)factory.GetCharactor("A");
ca.SetPointSize(12);
ca.Display();
![]()
// Charactor "B"
CharactorB cb = (CharactorB)factory.GetCharactor("B");
ca.SetPointSize(10);
ca.Display();
![]()
// Charactor "C"
CharactorC cc = (CharactorC)factory.GetCharactor("C");
ca.SetPointSize(14);
ca.Display();
}
}
0
相关文章