State pattern in action
Imagine, we are writing text processor. One of requirements to text processors is to have three fonts:
- font 1: A
- font 2: A
- font 3: A
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; 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");
}}public enum Fonts{ Font_1, Font_2, Font_3,}
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
- we can have so many `if else` statements in ` OnKeyUp ()` method after adding new fonts. So this code becomes unmaintainable
- our method becomes bigger and bigger if we add new fonts
So let’s try to implement in another way using State pattern:
Our text processor will look like this:
public class TextProcessor{ public void OnKeyUp(Font myFont) { myFont.OnKeyUp(); }}
Our abstract Font class:
public abstract class Font{ public abstract void OnKeyUp();}
and its implementations:
public class Font_1 : Font{ public override void OnKeyUp() { Console.WriteLine("Font_1 is chosen"); }}public class Font_2 : Font{ public override void OnKeyUp() { Console.WriteLine("Font_2 is chosen"); }}
public class Font_3 : Font{ public override void OnKeyUp() { Console.WriteLine("Font_3 is chosen"); }}
and then we can call our text processor like this:
static void Main(string[] args) { var textProcessor = new TextProcessor(); textProcessor.OnKeyUp(new Model.Fonts.Font_1()); }
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
Open closed principle is a principle which basically says «open for extension, closed for modification». This is one of the SOLID principles.