用来支持大量重复的数据的存储,比如很多相同的图元要存储在不同的图片/文档。
1)Flyweight:能对extrinsic state(外在状态)接收 和相应的接口。
public abstract class Flyweight
{
public abstract void Operation(int extrinsicState);
}
2) ConcereteFlyweight:实现Flyweight接口的类
public class ConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicState)
{
Console.WriteLine("Concrete Flyweight "+extrinsicState);
}
}
3)FlyweightFacotory:(Hashtable/Dictionary)
1.负责创建和管理Flyweight objects
2.确保flyweight能够被正确的共享。如果客户请求一个Flyweight,首先检查存在,如果存在,则返回;否则新创建一个对象。
public class FlyweightFactory
{
private static readonly Hashtable flyweights = new Hashtable();
public static Flyweight GetFlyweight(int key)
{
if (flyweights.Contains(key))
return flyweights[key] as Flyweight;
flyweights.Add(key, new ConcreteFlyweight());
return flyweights[flyweights.Count] as Flyweight;
}
}
4).客户端:只有Flyweight的引用,并且负责保持/存储extrinsicSate(外在的状态信息)。
public class Client1
{
void Call()
{
// Arbitrary extrinsic state
int extrinsicstate = 1;
Flyweight flyweight1 = FlyweightFactory1.GetFlyweight(extrinsicstate);
flyweight1.Operation(extrinsicstate);
extrinsicstate--;
Flyweight flyweight2 = FlyweightFactory1.GetFlyweight(extrinsicstate);
flyweight2.Operation(extrinsicstate);
extrinsicstate += 1;
}
}