/** * flyweight.h * Implemented by Blueprint Technologies, Inc. */ #ifndef _flyweight_h #define _flyweight_h #include #include #include using namespace std; /** * Abstract data type for the pattern. */ class ExtrinsicState { }; /** * Declares an interface through which flyweights can receive * and act on extrinsic state. */ class Flyweight { public: virtual void operation( ExtrinsicState* state ) = 0; }; /** * Implements the Flyweight interface and adds storage for intrinsic * state, if any. A ConcreteFlyweight object must be sharable. Any state * it stores must be intrinsic; that is, it must be independent of the * ConcreteFlyweight object's context. */ class ConcreteFlyweight: public Flyweight { public: virtual void operation( ExtrinsicState* state ) { }; }; /** * Not all Flyweight subclasses need to be shared. The Flyweight interface * enables sharing; it doesn't enforce it. It's common for UnsharedConcreteFlyweight * objects to have ConcreteFlyweight objects as children at some level * in the flyweight object structure (as the Row and Column classes have). */ class UnsharedConcreteFlyweight: public Flyweight { public: virtual void operation( ExtrinsicState* state ) { }; }; /** * Creates and manages flyweight objects. Ensures that flyweights are shared * properly. When a client requests a flyweight, the FlyweightFactory * object supplies an existing instance or creates one, if none exists. */ typedef pair< string, Flyweight* > FlyweightPair; class FlyweightFactory { private: vector< FlyweightPair > flyweights; public: Flyweight* getFlyweight( string key ) { vector< FlyweightPair >::iterator i; int found = 1; for( i = flyweights.begin(); i != flyweights.end(); ++i ) { FlyweightPair fp = *i; if( fp.first == key ) { return fp.second; } } FlyweightPair fp; fp.first = key; fp.second = new ConcreteFlyweight(); flyweights.push_back( fp ); return fp.second; }; }; #endif