标签:
1 // -------------------------------------------------------------------------------------- 2 /** Abstract.h **/ 3 4 class Abstract { 5 private: 6 typedef map<type_t, Abstract*> RegMap; 7 static RegMap& getRegistry() { 8 static RegMap registry; // initialized at the first time the function is called 9 return registry; 10 } 11 public: 12 Abstract(const type_t& type) { 13 if (lookup(type) != NULL) 14 getRegistry.insert(type, this); 15 } 16 17 virtual ~Abstract() { } 18 19 virtual Abstract* clone() = 0; 20 21 static Abstract* create(const type_t& type) { 22 Abstract* stub = lookup(type); 23 return stub != NULL : stub->clone() : NULL; 24 } 25 26 virtual void destroy() { delete this; } 27 28 static const Abstract* lookup(const type_t& type) { 29 if (getRegistry().find(type) != getRegistry().end()) 30 return getRegistry()[type]; 31 return NULL; 32 } 33 }; 34 35 // -------------------------------------------------------------------------------------- 36 /** ConcreteA.h **/ 37 38 class ConcreteA : public Abstract { 39 // ... data members 40 ConcreteA* clone() { return new ConcreteA(*this); } 41 public: 42 ConcreteA() : Abstract(CONC_TYPE_A) { } // CONC_TYPE_A : constant 43 // ... other members 44 }; 45 46 // -------------------------------------------------------------------------------------- 47 /** ConcreteA.cpp **/ 48 49 static ConcreteA __concrete_a_stub/*(...)*/; // static initialized 50 51 // -------------------------------------------------------------------------------------- 52 /** ConcreteB.h **/ 53 54 class ConcreteB : public Abstract { 55 // ... data members 56 ConcreteB* clone() { return new ConcreteB(*this); } 57 public: 58 ConcreteB() : Abstract(CONC_TYPE_B) { } // CONC_TYPE_B : constant 59 // ... other members 60 }; 61 62 // -------------------------------------------------------------------------------------- 63 /** ConcreteB.cpp **/ 64 65 static ConcreteB __concrete_b_stub/*(...)*/; 66 67 // -------------------------------------------------------------------------------------- 68 /** Client **/ 69 70 Abstract* p_abstract = Abstract::create(CONC_TYPE_A /* or CONC_TYPE_B */); 71 // ... some code 72 p_abstract->destroy(); 73 74 // --------------------------------------------------------------------------------------
标签:
原文地址:http://www.cnblogs.com/bestofme/p/4767657.html