设计模式之简单工厂模式
就是所有的类都在一个工厂内实现,显得臃肿
#include<iostream> using namespace std; #include<string> //抽象水果 class abstractFruit{ public: virtual void showName()=0; }; //苹果 class apple:public abstractFruit{ public: virtual void showName() { cout<<"apple"<<endl; } }; //梨 class pear:public abstractFruit{ public: virtual void showName() { cout<<"pear"<<endl; } }; //香蕉 class banana:public abstractFruit{ public: virtual void showName() { cout<<"banana"<<endl; } }; //水果工厂 class fruitFactory{ public: static abstractFruit* createFruit(string s) { if(s=="apple"){ return new apple; }else if(s=="pear"){ return new pear; }else if(s=="banana"){ return new banana; }else{ return NULL; } } }; int main() { fruitFactory *ff=new fruitFactory; abstractFruit* ap=ff->createFruit("apple"); ap->showName(); abstractFruit* pr=ff->createFruit("pear"); pr->showName(); abstractFruit* ba=ff->createFruit("banana"); ba->showName(); delete ap; delete pr; delete ba; delete ff; return 0; }