Strategy Pattern
Example 1
#include <iostream> using namespace std; // this is going to be injected to the main class class Algorithm { public: // abstract class virtual void action() =0; virtual ~Algorithm() { } }; class Algo1 : public Algorithm { public: void action() { cout << "Algo1 action " << endl; } }; class Algo2 : public Algorithm { public: void action() { cout << "Algo2 action " << endl; } }; class MainClass { public: // no return type means a constructor // MainClass( Algorithm * alg) { // this->myAlgo = alg; // } virtual ~MainClass(){ } Algorithm *myAlgo; void act() { myAlgo->action(); } void setAction(Algorithm * alg) { this->myAlgo = alg; } virtual void display() = 0; // pure virtual function }; class SubClass : public MainClass { public: SubClass() { myAlgo = new Algo1(); } void display() { cout << "display" << endl; } }; int main() { MainClass *m= new SubClass(); m->display(); m->act(); m->setAction(new Algo2); m->act(); cout << "Hello world!" << endl; return 0; }
display
Algo1 action
Algo2 action
Hello world!
Process returned 0 (0x0) execution time : 0.025 s
Press any key to continue.
Comments
Post a Comment