Design Pattern 2: Strategy Pattern)
Strategy defines a family of algorithms that encapsulate a series of algorithms, but they can be replaced by each other. The policy mode separates the changes of algorithms from those of their callers.
The UML diagram is as follows:
It mainly includes:
Strategy: declares an interface class that is common to all algorithms. The following Contex class uses this interface to call a specific Stragety algorithm. ConcreteStrategy: The algorithm class Context embodied using the Strategy interface: uses a pointer to a specific Strategy to operate on this specific Strategy object.
The following is the C ++ code written based on the above UML diagram:
#include
#include
#include
class Strategy{ public: virtual void algorithmInterface()=0;};class ConcreteStrategyA:public Strategy{ public: void algorithmInterface() { std::cout<<"ConcreteStrategyA::algorithmInterface()"<
algorithmInterface(); } private: Strategy* strategy;};int main(){ Context context; Strategy *sa=new ConcreteStrategyA(); Strategy *sb=new ConcreteStrategyB(); Strategy *sc=new ConcreteStrategyC(); context.setStrategy(sa); context.contextInterface(); context.setStrategy(sb); context.contextInterface(); context.setStrategy(sc); context.contextInterface(); delete sa; delete sb; delete sc; return 0;}
The execution result is as follows:
A specific example:
# Include
# Include
# Include
# Include
# Include
# Include using namespace std;/* an example of a specific policy mode * Strategy is SortStrategy * ConcreteStrategy is QuickSort, ShellSort, mergeSort * Contex is SortedList ** // The parent class SortStrategy {public: virtual void sort (list
& Lists) = 0 ;}; class QuickSort: public SortStrategy {public: void sort (list
& Lists) {std: cout <"QuickSort: sort" <
& Lists) {std: cout <"ShellSort: sort" <
& Lists) {std: cout <"Merge: sort" <
Sort (lists); print ();} void setSortStrategy (SortStrategy * s) {sortStrategy = s;} void add (string str) {lists. push_back (str);} void print () {list
: Iterator iter; for (iter = lists. begin (); iter! = Lists. end (); iter ++) {std: cout <* iter <
Lists; SortStrategy * sortStrategy;}; int main () {SortList sortList; sortList. add ("allan"); sortList. add ("john"); sortList. add ("harrison"); QuickSort * qs = new QuickSort (); ShellSort * ss = new ShellSort (); MergeSort * ms = new MergeSort (); sortList. setSortStrategy (qs); sortList. sort (); sortList. setSortStrategy (ss); sortList. sort (); sortList. setSortStrategy (MS); sortList. sort (); delete qs; delete ss; delete MS; return 0 ;}
Execution result: (add the corresponding sorting function to the specific location)