Factory method model (Factory Method) (rpm)

concept

Define an interface for creating an object, but let subclasses decide which class to instantiate technology. Factory Method to make a class instance to delay its subclasses.

Mode structure

1559921156257

Simple factory pattern comparison

Get back to simple factory pattern in the calculator example, if we need to add a new method of calculation, we need to add Operator subclass, and joined Case statement in the factory method to judge. This is clearly contrary to the open - closed principle.

Therefore, according to the factory method pattern dependent reverse principle, the abstract factory class an interface that only one way is to create a factory method abstract products. Then all the class factory to produce concrete went implement this interface, so that a simple pattern plant into a plant factory class abstract interface objects and a plurality of specific production plant.

As shown below:

1559922092613

Examples of patterns and analysis

#include <string>
#include <iostream> using namespace std; class LeiFeng { public: virtual void Sweep() { cout << "LeiFeng sweep" << endl; } }; //学雷锋的学生,对应于ConcreteProduct class Student : public LeiFeng { public: virtual void Sweep() { cout << "Student sweep" << endl; } }; //学雷锋的志愿者,对应于ConcreteProduct class Volunteer : public LeiFeng { public: virtual void Sweep() { cout << "Volunteer sweep" << endl; } }; //工厂抽象基类 Creator class LeiFengFactory { public: virtual LeiFeng * CreateLeiFeng() { return new LeiFeng(); } }; //工厂具体类 class StudentFactory : public LeiFengFactory { public: virtual LeiFeng * CreateLeiFeng() { return new Student(); } }; //工厂具体类 class VolunteerFactory : public LeiFengFactory { public: virtual LeiFeng* CreateLeiFeng() { return new Volunteer(); } }; int main() { LeiFengFactory * factory = new LeiFengFactory(); LeiFeng * student = new Student(); LeiFeng * volunteer = new Volunteer(); student->Sweep(); volunteer->Sweep(); delete factory; delete student; delete volunteer; return 0; }

Move determine client implementation, adding new features do not modify the original class, you can directly modify the client.

Guess you like

Origin www.cnblogs.com/strugglerisnd/p/10990337.html