simple_factory
#include <stdlib.h> #include <iostream> using namespace std; class Product { public: virtual ~Product() {} virtual int Interface()=0; }; class ConcreteProductA : public Product { public: ConcreteProductA() {} virtual ~ConcreteProductA() {} int Interface() { cout<<"Make my ProductA good!"<<endl; return -1; } }; class ConcreteProductB : public Product { public: ConcreteProductB() {} virtual ~ConcreteProductB() {} int Interface() { cout<<"Make my ProductB better!"<<endl; return 0; } }; class ConcreteProductC : public Product { public: ConcreteProductC() {} virtual ~ConcreteProductC() {} int Interface() { cout<<"Make my ProductC best!"<<endl; return 1; } }; #define PRODUCTA 1 #define PRODUCTB 2 #define PRODUCTC 3 class SimpleFactory { public: static Product* CreateProduct(int iType) { switch(iType) { case PRODUCTA: return new ConcreteProductA; case PRODUCTB: return new ConcreteProductB; case PRODUCTC: return new ConcreteProductC; default: { cerr<<"Sorry, I have not the product you need!"<<endl; return NULL; } } } }; #define CUSTOMER main #define DESTROY(ptr) if (ptr) { delete ptr; ptr = NULL; } int CUSTOMER(int argc, char** argv) { Product* pProduct = NULL; pProduct = SimpleFactory::CreateProduct(PRODUCTA); pProduct->Interface(); DESTROY(pProduct); pProduct = SimpleFactory::CreateProduct(PRODUCTB); pProduct->Interface(); DESTROY(pProduct); pProduct = SimpleFactory::CreateProduct(PRODUCTC); pProduct->Interface(); DESTROY(pProduct); return EXIT_SUCCESS; }