簡單工廠模式 c++實現
阿新 • • 發佈:2019-01-10
#include<stdio.h> #include<iostream> using namespace std; class Product{ public: virtual void run() = 0; }; class ProductA : public Product{ void run(){cout<<"Product A"<<endl;}; }; class ProductB : public Product{ void run(){cout<<"Product B"<<endl;}; }; class Factory{ public: Factory(){}; Product * create(int type){ switch(type){ case 0 : product = new ProductA; break; case 1 : product = new ProductB; break; default : cout<<"other products"<<endl; } return product; }; private: Product * product; }; int main(){ Factory * f = new Factory; Product * d = f->create(0); d->run(); d = f->create(1); d->run(); d = f->create(2); return 0; }