[Design Pattern] Factory Method Pattern

In the simple factory model, the responsibilities of the factory class are too important. If the design of a specific button is handed over to the subclasses of the factory, they can implement the methods defined in the abstract factory class, which can guarantee opening and closing. in principle.

http://design-patterns.readthedocs.org/zh_CN/latest/creational_patterns/factory_method.html

../_images/FactoryMethod.jpg


/*
 * concreteFactory.cpp
 *
 *  Created on: 2016年2月22日
 *      Author: chenwei
 */
#include "ConcreteFactory.h"
#include "ConcreteProduct.h"

Product* ConcreteFactory::factoryMethod() {
	return new ConcreteProduct();
}



/*
 * ConcreteMain.cpp
 *
 *  Created on: 2016年2月22日
 *      Author: chenwei
 */
#include "Factory.h"
#include "ConcreteFactory.h"
#include "Product.h"
#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
	Factory* fc = new ConcreteFactory();
	Product* prod = fc->factoryMethod();
	prod->use();

	delete fc;
	delete prod;

	return 0;
}



In this way, object-oriented polymorphism is used, and the core factory class is no longer responsible for the creation of specific production films, but is handed over to the factory subclass to do it, allowing the introduction of new products without modifying the factory class.

The disadvantage is that when new product categories are needed, new factory categories need to be added. The number of categories increases in pairs, which increases the difficulty of the system to a certain extent.

The application of the factory method pattern includes: a class does not know the object it needs; a class specifies which object to create through its subclasses; delegates the task of creating an object to one of multiple factory subclasses, the client In use, you don't need to care about which factory subclass creates the product subclass, and then dynamically specify it when needed.

Guess you like

Origin blog.csdn.net/michellechouu/article/details/50718967