Factory
Method:(1)、意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使一个类的实例化延迟到其子类;(2)、适用性:当一个类不知道它所必须创建的对象的类的时候;当一个类希望由它的子类来指定它所创建的对象的时候;当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
示例代码1:
#include <string> #include <iostream> using namespace std; //实例基类,相当于Product(为了方便,没用抽象) class LeiFeng { public: virtual void Sweep() { cout<<"雷锋扫地"<<endl; } }; //学雷锋的大学生相当于ConcreteProduct class Student : public LeiFeng { public: virtual void Sweep() { cout<<"大学生扫地"<<endl; } }; //学雷锋的志愿者,相当于ConcreteProduct class Volenter : public LeiFeng { public: virtual void Sweep() { cout<<"志愿者扫地"<<endl; } }; //工厂基类 Creator class LeiFangFactory { public: virtual LeiFeng* CreateLeiFeng() { return new LeiFeng(); } }; //工厂具体类 class StudentFactory : public LeiFangFactory { public: virtual LeiFeng* CreateLeiFeng() { return new Student(); } }; class VolenterFactory : public LeiFangFactory { public: virtual LeiFeng* CreateLeiFeng() { return new Volenter(); } }; //客户端 int main() { LeiFangFactory* sf = new LeiFangFactory(); LeiFeng *s = sf->CreateLeiFeng(); s->Sweep(); delete s; delete sf; /*result: 雷锋扫地 */ return 0; } |
示例代码2:
product.h:
#ifndef _PRODUCT_H_ #define _PRODUCT_H_ class Product { public: virtual ~Product() = 0; protected: Product(); private: }; class ConcreteProduct : public Product { public: ~ConcreteProduct(); ConcreteProduct(); protected: private: }; #endif// ~_PRODUCT_H_ |
product.cpp:
#include "product.h" #include <iostream> using namespace std; Product::Product() { } Product::~Product() { } ConcreteProduct::ConcreteProduct() { cout<<"ConcreteProduct ..."<<endl; } ConcreteProduct::~ConcreteProduct() { } |
factory.h:
#ifndef _FACTORY_H_ #define _FACTORY_H_ class Product; class Factory { public: virtual ~Factory() = 0; virtual Product* CreateProduct() = 0; protected: Factory(); private: }; class ConcreteFactory : public Factory { public: ~ConcreteFactory(); ConcreteFactory(); Product* CreateProduct(); protected: private: }; #endif//~_FACTORY_H_ |
factory.cpp:
#include "factory.h" #include "product.h" #include <iostream> using namespace std; Factory::Factory() { } Factory::~Factory() { } ConcreteFactory::ConcreteFactory() { cout<<"ConcreteFactory ..."<<endl; } ConcreteFactory::~ConcreteFactory() { } Product* ConcreteFactory::CreateProduct() { return new ConcreteProduct(); } |
main.cpp:
#include "factory.h" #include "product.h" #include <iostream> using namespace std; int main() { Factory* fac = new ConcreteFactory(); Product* p = fac->CreateProduct(); /*result: ConcreteFactory ... ConcreteProduct ... */ return 0; } |
工厂方法模式结构图:
|