三、單純享元模式的示意性源代碼
// Flyweight pattern -- Structural example
using System;
using System.Collections;
// "FlyweightFactory"
class FlyweightFactory
{
// FIElds
private Hashtable flyweights = new Hashtable();
// Constructors
public FlyweightFactory()
{
flyweights.Add("X", new ConcreteFlyweight());
flyweights.Add("Y", new ConcreteFlyweight());
flyweights.Add("Z", new ConcreteFlyweight());
}
// Methods
public Flyweight GetFlyweight(string key)
{
return((Flyweight)flyweights[ key ]);
}
}
// "Flyweight"
abstract class Flyweight
{
// Methods
abstract public void Operation( int extrinsicstate );
}
// "ConcreteFlyweight"
class ConcreteFlyweight : Flyweight
{
private string intrinsicstate = "A";
// Methods
override public void Operation( int extrinsicstate )
{
Console.WriteLine("ConcreteFlyweight: intrinsicstate {0}, extrinsicstate {1}",
intrinsicstate, extrinsicstate );
}
}
/**//// <summary>
/// ClIEnt test
/// </summary>
public class ClIEnt
{
public static void Main( string[] args )
{
// Arbitrary extrisic state
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
// Work with different flyweight instances
Flyweight fx = f.GetFlyweight("X");
fx.Operation( --extrinsicstate );
Flyweight fy = f.GetFlyweight("Y");
fy.Operation( --extrinsicstate );
Flyweight fz = f.GetFlyweight("Z");
fz.Operation( --extrinsicstate );
}
}