Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Namespace Flyweight
{
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
String document = "AAZZBBZBAAZZBBZBAAZZBBZB ";
Char [] chars = document. ToCharArray ();
Int charsCount = 0;
CharacterFactory factory = new CharacterFactory ();
Foreach (char c in chars)
{
CharsCount ++;
Character character = factory. GetCharacter (c );
Response. Write (character. Display (charsCount, "# 0000FF "));
}
Response. Write ("Total" + charsCount + "character ");
}
}
}
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 characloud (); break;
Case 'B': character = new CharacterB (); break;
//...
Case 'Z': character = new CharacterZ (); break;
}
_ Characters. Add (key, character );
}
Return character;
}
}
/// <Summary>
/// The 'flywith' abstract class
/// </Summary>
Abstract class Character
{
Protected char symbol;
Protected int width;
Protected int height;
Protected string color;
Protected int descent;
Protected int fontsize;
Public string Display (int fontsize, string color)
{
This. fontsize = fontsize;
This. color = color;
Return "<font size =" + fontsize + "COLOR =" + color + ">" + this. symbol + "</FONT> ";
}
}
/// <Summary>
/// A' ConcreteFlyweight 'class
/// </Summary>
Class characloud: Character
{
// Constructor
Public characloud ()
{
This. symbol = 'a ';
}
// Public override string Display (int fontsize, string color)
//{
// This. fontsize = fontsize;
// This. color = color;
// Return "<font size =" + fontsize + "COLOR =" + color + ">" + this. symbol + "</FONT> ";
//}
}
/// <Summary>
/// A' ConcreteFlyweight 'class
/// </Summary>
Class CharacterB: Character
{
// Constructor
Public CharacterB ()
{
This. symbol = 'B ';
}
}
Class CharacterZ: Character
{
// Constructor
Public CharacterZ ()
{
This. symbol = 'Z ';
}
}