简单工厂模式,一个工厂,多个产品;增加一种产品,就要修改工厂类中的代码,违反了对扩展开放,对修改关闭原则,会使得代码边的臃肿
#include <iostream> using namespace std; class Product { public: virtual void show()=0; }; class PA:public Product { public: void show() { cout<<"this is a"<<endl; return ; } }; class PB:public Product { public: void show() { cout<<"this is b"<<endl; return ; } }; class Factroy { public: Product* create(int i) { switch (i) { case 1: return new PA(); break; case 2: return new PB(); break; default: return nullptr; } return nullptr; } }; int main() { Factroy f; f.create(1)->show(); f.create(2)->show(); return 0; }
定义一个创建对象的接口, 让其子类自己决定实例化哪一个工厂类,多个工厂多个产品,当增加一个新产品时,同时增加一个新工厂。增加新工厂属于扩展,不会修改以前工厂类和产品类的任何代码。
#include <iostream> using namespace std; class Product { public: virtual void show()=0; }; class PA:public Product { public: void show() { cout<<"this is a"<<endl; return ; } }; class PB:public Product { public: void show() { cout<<"this is b"<<endl; return ; } }; class Factroy { public: virtual Product* create()=0; }; class FA:public Factroy { public: Product* create() { return new PA(); } }; class FB:public Factroy { public: Product* create() { return new PB(); } }; int main() { FA fa; fa.create()->show(); FB fb; fb.create()->show(); return 0; }