using System;
using System.Collections;
namespace ConsoleApplication5
{
class Program
{
/// <summary>
/// 在软件开发过程,如果我们需要重复使用某个对象的时候,
/// 如果我们重复地使用new创建这个对象的话,这样我们在内存就需要多次地去申请内存空间了,
/// 这样可能会出现内存使用越来越多的情况,这样的问题是非常严重,然而享元模式可以解决这个问题,
/// 下面具体看看享元模式是如何去解决这个问题的。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
CharactorFactory factory = new CharactorFactory();
// Charactor "A"
CharactorA ca = (CharactorA)factory.GetCharactor("A");
ca.SetPointSize();
ca.Display();
// Charactor "B"
CharactorB cb = (CharactorB)factory.GetCharactor("B");
cb.SetPointSize();
cb.Display();
// Charactor "C"
CharactorC cc = (CharactorC)factory.GetCharactor("C");
cc.SetPointSize();
cc.Display();
}
}
// 字符工厂(负责创建和管理享元对象)
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;
}
}
/// <summary>
/// 字符特殊类,提供具体享元类具有的方法
/// </summary>
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();
}
/// <summary>
/// 字符A
/// </summary>
public class CharactorA : Charactor
{
// Constructor
public CharactorA()
{
this._symbol = 'A';
this._height = ;
this._width = ;
this._ascent = ;
this._descent = ;
this._pointSize = ;
}
//Method
public override void SetPointSize(int size)
{
this._pointSize = size;
}
public override void Display()
{
Console.WriteLine(this._symbol +
"pointsize:" + this._pointSize);
}
}
/// <summary>
/// 字符B
/// </summary>
public class CharactorB : Charactor
{
// Constructor
public CharactorB()
{
this._symbol = 'B';
this._height = ;
this._width = ;
this._ascent = ;
this._descent = ;
this._pointSize = ;
}
//Method
public override void SetPointSize(int size)
{
this._pointSize = size;
}
public override void Display()
{
Console.WriteLine(this._symbol +
"pointsize:" + this._pointSize);
}
}
/// <summary>
/// 字符C
/// </summary>
public class CharactorC : Charactor
{
// Constructor
public CharactorC()
{
this._symbol = 'C';
this._height = ;
this._width = ;
this._ascent = ;
this._descent = ;
this._pointSize = ;
}
//Method
public override void SetPointSize(int size)
{
this._pointSize = size;
}
public override void Display()
{
Console.WriteLine(this._symbol +
"pointsize:" + this._pointSize);
}
}
}