享元模式:
示例代码:
- Flyweight类,它是所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。
abstract class Flyweight {
public abstract void Operation(int extrinsicstate);
}
- ConcreteFlyweight是继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
class ConcreteFlyweight : Flyweight {
public override void Operation(int extrinsicstate) {
Console.WriteLine("具体Flyweight:" + extrinsicstate);
}
}
- UnsharedConcreteFlyweight是指那些不需要共享的Flyweight子类。因为Flyweight接口共享成为可能,但它并不强制共享。
class UnsharedConcreteFlyweight : Flyweight {
public override void Operation(int extrinsicstate) {
Console.WriteLine("不共享的具体Flyweight:" + extrinsicstate);
}
}
- FlyweightFactory,是一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理地共享Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个( 如果不存在的话)。
class FlyweightFactory {
private Hashtable flyweights = new Hashtable();
//初始化工厂时,先生成三个实例
public FlyweightFactory() {
flyweights.Add("X", new ConcreteFlyweight());
flyweights.Add("Y", new ConcreteFlyweight());
flyweights.Add("Z", new ConcreteFlyweight());
}
//根据客户端请求,获得已生成的实例
public Flyweight GetFlyweight(String key) {
return ((Flyweight) flyweights[key]);
}
}
static void Main(String[] args) {
//代码外部状态
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.GetFlyweight("X");
fx.Operation(--extrinsicstate);
Flyweight fy = f.GetFlyweight("y");
fy.Operation(--extrinsicstate);
Flyweight fz = f.GetFlyweight("z");
fy.Operation(--extrinsicstate);
Flyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(--extrinsicstate);
Console.Read();
}
结果表示
具体Flyweight:21
具体Flyweight:20
具体Flyweight:19
不共享的具体Flyweight:18