Factory Method Pattern: Define an interface for creating objects and let subclasses instantiate which class. The factory method delays the instantiation of a class to its subclasses.
The difference from a simple factory: A simple factory needs to modify the original class, which violates the opening and closing principle. The factory method avoids this problem of classes. It maintains the advantages of encapsulating the object creation process and only needs to add a factory class, which solves the problem of simple factory branch judgment.
The factory method pattern contains four roles:
Product: abstract product
ConcreteProduct: concrete product
Factory: abstract factory
ConcreteFactory: Concrete factory
UML class diagram
Test case:
[code]int main(){ //工厂方法 IFactory *factory = new UnderGraduateFactory; //new一个大学生工厂 //创建学雷锋的学生 LeiFeng *student = factory->createLeiFeng(); //学生干了哪些雷锋方法 student->BuyRice(); //买米 student->Sweep(); //扫地 student->Wash(); //清洗 return 0; }
[code]class LeiFeng{ public: virtual void BuyRice(){ std::cout << "Buy rice.\n"; } virtual void Sweep(){ std::cout << "Sweep.\n"; } virtual void Wash(){ std::cout << "Wash.\n"; } };
[code]class UnderGraduate: public LeiFeng{ }; //学雷锋的志愿者(具体产品) class Volunteer: public LeiFeng{ };
[code]class IFactory{ public: //创建学雷锋对象 virtual LeiFeng* createLeiFeng(){ return NULL; } };
[code]class UnderGraduateFactory: public IFactory{ LeiFeng* createLeiFeng(){ return new UnderGraduate; } }; class VolunteerFactory: public IFactory{ LeiFeng* createLeiFeng(){ return new Volunteer; } };