[Design Mode] Simple Factory Mode

The factory class contains the necessary judgment logic to determine when to use an instance of which product class.

The abstract product class is the parent class of all objects created.

The specific product class is the creation target, inherited from the abstract product class.

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

../_images/SimpleFactory.jpg


#include "Factory.h"
#include "ConcreteProductA"
#include "ConcreteProductB"

Product* Factory::createProduct(string proname) {
	if ('A' == proname) {
		return new ConcreteProductA();
	}
	else if('B' == proname) {
		return new ConcreteProductB();
	}
}


The advantage of the factory pattern is that when you need something, you only need to pass in a correct parameter to get the object you need without knowing the creation details, see above
createProduct()

Factory methods of factory classes are often static methods, which can be called directly by the class name. It is very convenient to use.

The simple factory model separates the creation of the object from the business processing of the object itself, reduces the system and coupling, and makes it relatively easy to modify both.

The problem is that the factory class has too heavy responsibilities, and the addition of new products requires modification of related logic, which does not conform to the opening and closing principles of software development (open for extension, closed for modification). And once the factory class cannot work, it will affect the entire system.

The simple factory model uses a static factory method, which makes it impossible for factory roles to form a hierarchy based on inheritance.

The static method is the behavior of the class and has nothing to do with the objects of the class

Guess you like

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