00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #ifndef __PROTOTYPE_INCLUDED
00019 #define __PROTOTYPE_INCLUDED
00020
00021 #include <map>
00022 #include <string>
00023
00024 #include "common/defs.h"
00025
00026
00027
00028
00029
00030
00031
00032 class TCanBePrototype
00033 {
00034 public:
00038 virtual ~TCanBePrototype()
00039 {
00040 LOG("TCanBePrototype","~TCanBePrototype") << fTypeName << " deleted" << endl;
00041 }
00042
00048 virtual TCanBePrototype* clone() const = 0;
00052 const string& getTypeName() const
00053 {
00054 return fTypeName;
00055 }
00059 void setTypeName( const string& name )
00060 {
00061 fTypeName = name;
00062 }
00063
00064 protected:
00068 TCanBePrototype() { };
00069
00070 private:
00074 std::string fTypeName;
00075 };
00076
00077
00078
00079
00080
00081
00082
00083 template<class KEY, class VALUE> class TPrototypeManager
00084 {
00085 public:
00089 ~TPrototypeManager()
00090 {
00091 reset();
00092 }
00093
00100 VALUE* create( const KEY& key )
00101 {
00102 VALUE* proto = find( key );
00103 if ( proto == 0 ) return 0;
00104
00105 LOG("TPrototypeManager","create") << "creating object from prototype: " << proto->getTypeName() << endl;
00106 return dynamic_cast<VALUE*>( proto->clone() );
00107 }
00112 VALUE* find( const KEY& key ) const
00113 {
00114 typename std::map<KEY,VALUE*>::const_iterator it = fPrototypes.find(key);
00115 if ( it == fPrototypes.end() ) {
00116 LOG("TPrototypeManager","find") << "info: key not found!" << endl;
00117 return 0;
00118 }
00119 return it->second;
00120 }
00126 static TPrototypeManager<KEY,VALUE>& instance()
00127 {
00128 static TPrototypeManager<KEY,VALUE> theInstance;
00129 return theInstance;
00130 }
00139 bool registerPrototype( KEY key, VALUE* prototype )
00140 {
00141 if ( prototype == 0 ) return false;
00142
00143 LOG("TPrototypeManager", "registerPrototype")
00144 << "register new prototype: " << prototype->getTypeName() << endl;
00145
00146 typename std::map<KEY,VALUE*>::iterator it = fPrototypes.find(key);
00147 if ( it != fPrototypes.end() ) {
00148 LOG("TPrototypeManager", "registerPrototype")
00149 << "another prototype with the same key does already exist => delete this element" << endl;
00150 delete it->second;
00151 }
00152 fPrototypes[key] = prototype;
00153 return true;
00154 }
00159 void reset()
00160 {
00161 typename std::map<KEY,VALUE*>::iterator it;
00162
00163 LOG("TPrototypeManager", "reset") << "reset called" << endl;
00164 for ( it=fPrototypes.begin(); it!=fPrototypes.end(); it++ ) {
00165 delete it->second;
00166 }
00167 fPrototypes.clear();
00168 }
00169
00170 protected:
00176 TPrototypeManager<KEY,VALUE>()
00177 {
00178 LOG("TPrototypeManager","TPrototypeManager") << "prototype manager created" << endl;
00179 };
00180
00181 private:
00185 typename std::map<KEY,VALUE*> fPrototypes;
00186 };
00187
00188
00189
00190
00191
00192 #endif // __PROTOTYPE_INCLUDED