Strategy Design Pattern define a family of algorithms, encapsulate each one, and make then interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Class Diagram:
Class Diagram of real example:
Source Code of real example in C++:
/* * File:strategy.cpp * This file is described the strategy Design Pattern with help of example * Strategy pattern is structutal Pattern * Author: Aplha * Date: 31 Dec 2020 */ //Header File #include<iostream> //TreadMill Class (Base class of different strategy) class TreadMillStrategy { protected: int m_speed; public: virtual void Start() = 0; virtual void Stop() = 0; }; class ChildStrategy:public TreadMillStrategy { public: ChildStrategy(int speed){ m_speed = speed;} ~ChildStrategy(){} void Start() { if(SpeedRestriction()) { std::cout<<"Child TreadMill Mode Started, speed:"<<m_speed<<std::endl; //Call the Driver api to start the Motor } else { std::cout<<"Child TreadMill Mode Cannot start, speed is more"<<std::endl; } } void Stop() {std::cout<<"Child TreadMill Mode Stop"<<std::endl;} private: bool SpeedRestriction() { return (m_speed < 10) ? true : false;} }; //Adult TreadMill Mode class AdultStrategy:public TreadMillStrategy { public: AdultStrategy(int speed){ m_speed = speed; } ~AdultStrategy(){} void Start() { std::cout<<"Adult TreadMill Mode Started, speed:"<<m_speed<<std::endl; IncreaseSpeed(); std::cout<<"Adult TreadMill Mode speed increased, speed:"<<m_speed<<std::endl; } void Stop() {std::cout<<"Adult TreadMill Mode Stop"<<std::endl;} private: void IncreaseSpeed() { m_speed = m_speed + 10;} }; //Controller class Controller { TreadMillStrategy* m_st; public: Controller(TreadMillStrategy* tm): m_st(tm){} ~Controller(){} void SetStrategy(TreadMillStrategy* tr) { m_st = tr; std::cout<<"*************Changing Strategy at run tim*************"<<std::endl; } void StartInterface(){m_st->Start();} void StopInterface(){m_st->Stop();} }; //CLient int main() { // Strategy Pattern is Structutal Pattern so // Inside Controller we will not create of TreaMillStrategy // Below creation of different strategy can be done by Factory Pattern // Creation of different strategy is depend upon Client(HOw is using strategy) std::cout<<"Strategy Design Pattern"<<std::endl; TreadMillStrategy* tm = new ChildStrategy(5); Controller* con = new Controller(tm); con->StartInterface(); con->StopInterface(); ///////////////////////Change Strategy at run time; delete tm; tm = new AdultStrategy(10); con->SetStrategy(tm); con->StartInterface(); con->StopInterface(); delete tm; delete con; return 0; }
Compilation Command:
g++ -std=c++11 strategy.cpp
Output:
Strategy Design Pattern
Child TreadMill Mode Started, speed:5
Child TreadMill Mode Stop
*************Changing Strategy at run tim*************
Adult TreadMill Mode Started, speed:10
Adult TreadMill Mode speed increased, speed:20
Adult TreadMill Mode Stop