/*简单工厂设计模式 */ #include <iostream> using namespace std; class Fruit { /************************************************************************/ /* 创建一个抽象水果类 */ /************************************************************************/ public: virtual void getFruit()=0; protected: private: }; class Banana :public Fruit { public: virtual void getFruit(){ cout<<"香蕉"<<endl; } protected: private: }; class pear :public Fruit { public: void getFruit(){ cout<<"pear"<<endl; } protected: private: }; class Factory { /************************************************************************/ /* 创建一个工厂类,生产具体的水果 */ /************************************************************************/ public: static Fruit * Create(char *name){ Fruit * temp=NULL; if(strcmp(name,"banana")==0){ temp=new Banana(); }else if(strcmp(name,"pear")==0){ temp=new pear(); }else{ return NULL; } } protected: private: }; int main(){ Fruit *pear=Factory::Create("pear");
if(pear==NULL){ cout<<"生产失败"<<endl; } pear->getFruit(); Fruit *banana =Factory::Create("banana"); banana->getFruit(); char * a="xsaxa"; cout<< *a <<endl; return 0; }