Design patterns – Strategy


Hello guys,

I’m back with the Strategy pattern.

There are common situations when classes differ only in their behavior. For these cases it is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.

In order to implement this pattern, we will need the following:

  • A strategy base class (let’s call it ‘X’) with a virtual method (‘Y’) 
    • (the virtual method will be modified in all subclasses – the strategies)
  • A class (strategy implementation) that will:
    • keep a pointer to X and call its Y function
    • have a function to switch between strategies at runtime (by changing the X pointer to another strategical approach – a different subclass)

Let’s give an example:

  • std::sort algorithm – can receive the Compare concept as param. This will allow the user to define its own sorting mechanism.

 

Real example:

We have the following defined classes:

  • Abstract base class (interface) called ISort with virtual function called doSort

  • Two classes (BubbleSort, MergeSort) inheriting (public) from ISort, overwriting the doSort function

  • Class CStrategyImplementation that contains a pointer to ISort and a function to change the Sort pointer

 

Please note that I’ve removed the null pointer checks and the actual implementation, so the example from above is just a sketch of what the strategy pattern should look like.


The full code can be found at the following link:
https://github.com/badearobert/cplusplus

Leave a comment

Your email address will not be published.