Home >Backend Development >C#.Net Tutorial >A brief introduction to factory method pattern in C++ design patterns
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; }Lei Feng class (abstract product):
[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"; } };People who learn from Lei Feng (specific products):
[code]class UnderGraduate: public LeiFeng{ }; //学雷锋的志愿者(具体产品) class Volunteer: public LeiFeng{ };Lei Feng factory class ( Abstract Factory):
[code]class IFactory{ public: //创建学雷锋对象 virtual LeiFeng* createLeiFeng(){ return NULL; } };Learn from Lei Feng’s Object Factory (Concrete Factory):
[code]class UnderGraduateFactory: public IFactory{ LeiFeng* createLeiFeng(){ return new UnderGraduate; } }; class VolunteerFactory: public IFactory{ LeiFeng* createLeiFeng(){ return new Volunteer; } };The above is the content of a brief understanding of the factory method pattern in C++ design patterns. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!