简单工厂
#include <iostream> struct I_Pro { virtual void fun() = 0; }; class A : public I_Pro { public: virtual void fun(); }; void A::fun() { std::cout << "funA" << std::endl; } class B : public I_Pro { public: virtual void fun(); }; void B::fun() { std::cout << "funB" << std::endl; } struct I_Factry { virtual I_Pro* createPro(int type) = 0; }; class Factory : public I_Factry { virtual I_Pro* createPro(int type); }; I_Pro* Factory::createPro(int type) { I_Pro* ptr = nullptr; switch (type) { case 1: ptr = new A; break; case 2: ptr = new B; break; } return ptr; } int main() { I_Factry* ptr = new Factory;//不知这里factory还要搞个抽象类,莫非是为了以后有可能有多个工厂考虑的 I_Pro* pro = ptr->createPro(2); pro->fun(); getchar(); return 0; }
现在写这样的的比以前清晰很多。