Strategy pattern in action

Stepan Markakov
2 min readApr 2, 2021

Imagine, we are writing text processor. Now we have two requirements for our text processor:

- have three fonts

- add ability to color a text

So, text would look like this:

Desired fonts

Ok. We have understood a task. So let’s try to implement this task. One of the implementation would be:

public class TextProcessor{    private Fonts _currentFont;    private CustomColor _customColor;
public void OnKeyUp()
{ if (_currentFont == Fonts.Font_1) Console.WriteLine("Font_1 is chosen"); else if (_currentFont == Fonts.Font_2) Console.WriteLine("Font_2 is chosen"); else if (_currentFont == Fonts.Font_3) Console.WriteLine("Font_3 is chosen"); if (_customColor == CustomColor.Red) Console.WriteLine("Red color is chosen"); else if (_customColor == CustomColor.Green) Console.WriteLine("Green color is chosen"); else if (_customColor == CustomColor.Purple) Console.WriteLine("Purple color is chosen"); }
}

However, it is really not good implementation. The reasons why it is not good implementation:

- every time we need to modify class TextCanvas to add new Font type or new color

- we can have so many `if else` statements in ` OnKeyUp ()` method after adding new fonts or new color. So this code becomes unmaintainable

- our method becomes bigger and bigger if we add new fonts or colors

So let’s try to implement in another way using Strategy pattern:

Our text processor will look like this:

public class TextProcessor{    // new way: using polymorphism – base class or interface    public void OnKeyUp(Font myFont, Color color)    {         myFont.Apply();         color.Apply();    }}

Our abstract Font class:

public abstract class Font{    public abstract void Apply();}

and its implementation:

public class Font_1 : Font{    public override void Apply()    {        Console.WriteLine("Font_1 is chosen");    }}

Our abstract Color will look like this:

public abstract class Color{    public abstract void Apply();}

And implementations of abstract color class:

public class GreenColor : Color{    public override void Apply()    {        Console.WriteLine("The Green color is applied");    }}

It can be seen that this implementation is:

· cleaner and clearer.

· now we can add new functionality without editing existing classes

· moreover, this implementation keeps open closed principle

Some readers can notice that State and Strategy pattern has many similarities and it is true. So, I invite you to read my article about differences between State and Strategy pattern.

--

--

Stepan Markakov
0 Followers

I am software engineer. I like to learn and like to develop software. I program with C#, SQL and JavaScript