一.简单工厂模式
简单工厂模式是根据传入工厂类的参数,动态决定创建哪一类产品类
一个工厂类负责多个产品类,根据传进来的参数决定生产哪个产品
//产品类 class Product{ public: virtual void show()==0; }; class Product_A:public Product{ public: void show(){ cout<<"Product_A"<<endl; } }; class Product_B:public Product{ public: void show(){ cout<<"Product_B"<<endl; } };
//工厂类 class Factory{ public: Product* Create(int i){ switch(i){ case 1: return new Product_A; break; case 2: return new Product_B; break; default: break; } } };
//调用 int main(){ Factory* factory=new Factory(); factory->Create(1)->show(); factory->Create(2)->show(); }
二.工厂方法模式
多个工厂类对应多个产品类,一个工厂类对应一个产品类,互不干扰
//产品类 class Product{ public: virtual void show()=0; }; class Product_A:public Product{ public: void show(){ cout<<"Product_A"<<endl; } }; class Product_B:public Product{ public: void show(){ cout<<"Product_B"<<endl; } };
//工厂类 class Factory{ public: virtual Product* create()=0; }; class Factory_A:public Factory{ public: Product* create(){ return new Product_A; } }; class Factory_B:public Factory{ pubilc: Product* create(){ return new Product_B; } };
//调用 int main(){ Factory_A* productA=new Factory_A(); Factory_B* productB=new Factory_B(); productA->create()->show(); productB->create()->show(); }
三.抽象工厂模式
多个工厂类对应多个不同种类的产品类,一个工厂类对应一个种类多个产品类,互不干扰
//产品类 class Product1{ public: virtual void show()=0; }; class Product_A1:public Product1{ public: void show(){ cout<<"product_A1"<<endl; } }; class Product_B1:public Product1{ public: void shwo(){ cout<<"product_B1"<<endl; } }; class Product2{ public: virtual void show()=0; }; class product_A2:public Product2{ public: void show(){ cout<<"product_A2"<<endl; } }; class product_B2:public Product2{ public: void show(){ cout<<"product_B2"<<endl; } };
//工厂类 class Factory{ public: virtual Product1* create1()=0; virtaul Product2* create2()=0; }; class FactoryA{ public: Product1* create1(){ return new product_A1(); } Product2* create2(){ return new product_A2(); } }; class FactoryB{ public: Product1* create1(){ return new product_B1(); } Product2* create2(){ return new product_B2(); } };
int main(){ FactoryA* factoryA=new FactoryA(); factoryA->create1()->show(); factoryB->create2()->show(); FactoryB* factoryB=new FactoryB(); factoryB->create1()->show(); factoryB->create2()->show(); }