Policy Mode C + + implementation 1 definition
(Strategy Pattern) defines a set of algorithms that encapsulate each algorithm and enable them to replace each other.
Also called the policy model
2 class Diagram
3 implementation
Class strategy
{
Protected
Strategy ();
Public
Virtual ~strategy () = 0;
virtual void dosomething () = 0;
};
Class Concretestrategy1:public Strategy
{
Public
void DoSomething ()
{
cout << "Algorithms for Specific Strategy 1" <<endl;
}
};
Class Concretestrategy2:public Strategy
{
Public
void DoSomething ()
{
cout << "Algorithms for Specific Strategy 1" <<endl;
}
};
Encapsulating roles
Class Context
{
Private
Strategy * _STR;
Public
Context (Strategy * st)
: _str (ST)
{}
void Doanything ()
{
_str->dosomething ();
}
};
void Test
{
Strategy * st = new ConcreteStrategy1 ();
Context *con = new context (ST);
Con->doanything ();
}
4 applications
① Advantages
The algorithm is free to switch
Avoid using multiple criteria to judge. Transfer decision-making authority to senior level, you pass in the policy I can do it.
Good extensibility
② Disadvantages
Increased number of strategies
All the strategy classes will be out of the field, the upper level must know the specific strategy
Note: This drawback is can be remedied by other means eg factory method, proxy mode, enjoy meta mode
5 Usage Scenarios
Multiple classes are only slightly different on the algorithm
The algorithm needs to switch freely
Where the algorithm rules need to be masked. (Analogous function)
Note, a policy family should not have more than 4 specific policies, or use mixed mode to solve the problem of policy class expansion and external storm drain.
6 extensions
Enumeration policy
Definition: It is an enumeration that concentrates the enumeration of policy patterns
Enumeration attributes: Pubic,finaly,static
So in C + + it is actually a class that encapsulates multiple static methods. (half used as a role that does not change frequently)
eg Strategy::add ();
Strategy::sub (); .....
Design pattern--Strategy Mode C + + implementation