According to the information given, choose different strategies;
The difference between the strategy mode and the factory model
Personal Understanding (Factory mode: Create different objects from the information given
Policy mode: Choose a different strategy from the information given
)
- The use is not the same
Factory is a model of creation, its role is to create objects;
The strategy is the behavioral pattern, its function is to let an object choose one behavior in many behaviors;
The focus is different.
A Focus object creation
An act of concern encapsulation
Solve the different problems
The Factory mode is a design pattern of creation, it accepts the instruction, creates the instance which conforms to the requirement, it mainly solves the unified distribution of the resources, the creation of the object is completely independent, so that the object creation and the specific use of the customer is irrelevant. Main application in multi-database selection, class library file loading and so on.
The strategy mode is to solve the policy switching and extension, more concise is to define the policy family, respectively encapsulated, so that they can replace each other, the policy mode to make the policy changes independent of the customers using the policy.
The factory is equivalent to a black box, the strategy equivalent to white box.
//Strategy.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include<IOSTREAM>#include<string>using namespacestd;classpaint{ Public: Virtual voidPaint () =0;};classPaintbypen: Publicpaint{ Public: voidpaint () {cout<<"Use pen to paint"<<Endl; }};classPaintbypencil: Publicpaint{ Public: voidpaint () {cout<<"Use pencil to paint"<<Endl; }};classclient{ Public: Paint* Getpaint (stringtype) { if("Pen"==type) {m_p=NewPaintbypen; returnm_p; } if("Pencil"==type) {m_p=NewPaintbypencil; returnm_p; } }Private: Paint*m_p;};intMainintargcChar*argv[]) {Client* Pclient =NewClient; Paint* p = pclient->getpaint ("Pencil"); P-paint (); return 0;}
Policy Mode Strategy