/* Flyweight类 * 它是所有具体享元类的超类或接口,通过这个接口, * Flyweight可以接受并作用于外部状态。 */ class Flyweight { public: virtual void Operation( int extrinsicstate ) = 0; }; /* ConcreteFlyweight类 * ConcreteFlyweight是继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。 */ class ConcreteFlyweight : Flyweight { public: virtual void Operation( int extrinsicstate ) { printf("具体Flyweight:%d\n",extrinsicstate); } }; /* UnsharedConcreteFlyweight类 * 是指那些不需要共享的Flyweight子类。因为Flyweight接口共享成为可能,但并不强制共享。 */ class UnsharedConcreteFlyweight : public Flyweight { public: virtual void Operation( int extrinsicstate ) { printf("不共享的具体Flyweight:%d\n",extrinsicstate); } }; /* FlyweightFactory类 * 是一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理地共享Flyweight, * 当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或创建一个 * (如果不存在的话) */ class FlyweightFactory { private: Hashtable flyweights = new Hashtable(); public: Flyweight GetFlyweight(string key) { if( !flyweights.ContainKey(key) ) flyweights.add( key, new ConcreteFlyweight() ); return (Flyweight)flyweights[key]; } }; // 客户端 int main() { int extrinsicstate; // 代码外部状态 FlyweightFactory f = new FlyweightFactory(); Flyweight fx = f.GetFlyweight("X"); fx.Operation(--extrinsicstate); Flyweight fy = f.GetFlyweight("Y"); fy.Operation(--extrinsicstate); Flyweight uf = new UnsharedConcreteFlyweight(); uf.Operation(--extrinsicstate); }