Flyweight Pattern is user to reduce the amount or memory when you have many objects with a common part. So you separate the common part from the specialized part of the object and you reuse the common parte for all object.
For example you can create a cache class that stores a list of objects, these objects are common and you don't need to instantiate a new object if it is already instantiated previously. The Classic example is a Word processore that uses characters. The characters have a common part: font,size,color, and a specificare part, the characters itself : 'a', 'b', etc and when you use the characters 'a' you don't have to recreate the object again when you use it a second time.
class Character
{
int size;
string font;
Color color;
public void Character()
{
size = 8;
font = "Verdana";
color = Color.Red;
}
}
public class CharacterA : Character
{
char character;
public void CharacterA()
{
character = 'A';
}
}
public class CharacterB : Character
{
char character;
public void CharacterB()
{
character = 'B';
}
}
...
public class CharacterFactory
{
private Dictionary<char,Character> characterMap;
...
public Character GetCharacter(char character)
{
Character characterToReturn;
if (characterMap.ContainsKey(character))
{
characterToReturn = characterMap[character];
}
else
{
switch(character)
{
case 'A':
characterToReturn = new CharacterA();
case 'B':
characterToReturn = new CharacterB();
...
}
characterMap[character] = characterToReturn;
}
return characterToReturn;
}
}
Nessun commento:
Posta un commento