工厂类(Creator)用来负责创建对象,有一个抽象类,下面有很多子类用于创建具体的对象 实际对象的创建延迟 工厂类 #ifndef _CREATOR_H #define _CREATOR_H class Product; class Creator { public: Creator(){}; virtual ~Creator() = 0{}; // 用于创建实际对象 virtual Product* Puoduce() = 0; }; class CarCreator : public Creator { public: CarCreator(){}; virtual ~CarCreator(){}; Product* Puoduce(); }; class BusCreator : public Creator { public: BusCreator(){}; virtual ~BusCreator(){}; Product* Puoduce(); }; #endif Product* CarCreator::Puoduce() { Product* p = new Car(); return p; } Product* BusCreator::Puoduce() { Product* p = new Bus(); return p; } 产品类 #ifndef _PRODUCT_H #define _PRODUCT_H class Product { public: Product(); virtual ~Product() = 0; }; class Car : public Product { public: Car(); virtual ~Car(); }; class Bus : public Product { public: Bus(); virtual ~Bus(); }; #endif Product::Product() { cout<<"Product Constructor"; } Product::~Product() { cout<<"Product Destructor"; } Car::Car() { cout<<"Car Constructor"; } Car::~Car() { cout<<"Car Destructor"; } Bus::Bus() { cout<<"Bus Constructor"; } Bus::~Bus() { cout<<"Bus Destructor"; } int _tmain(int argc, _TCHAR* argv[]) { Creator* pCreator = new CarCreator(); Product* pProduct = pCreator->Puoduce(); // operations // delete pCreator; delete pProduct; return 0; }