1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| #ifndef FACTORY_H #define FACTORY_H #include <iostream> #include <string> #include <memory> #include <map> using namespace std;
class Products { public: virtual void productMethod() = 0; };
class car : public Products { public: void productMethod() { cout << " car " << endl; } };
class bus : public Products { public: void productMethod() { cout << " bus " << endl; } };
class BaseFactory { public: virtual Products* create() = 0; public: static map<string, BaseFactory*> fac; static Products* create_product(const string& name) { if (fac.find(name) != fac.end()) { return fac[name]->create(); } else { return NULL; } } };
map<string, BaseFactory*> BaseFactory::fac;
class carFactory : public BaseFactory { public: Products* create() { return new car(); } };
class busFactory : public BaseFactory { public: Products* create() { return new bus(); } };
class Init_BaseFac { static Init_BaseFac m_init; public: Init_BaseFac() { BaseFactory::fac["car"] = new carFactory(); BaseFactory::fac["bus"] = new busFactory(); } };
Init_BaseFac Init_BaseFac::m_init;
|