I need to get rid of that switch statement. What is the Strategy Pattern?

I’m a big advocate of software maintainability and there is nothing better for that than applying well known patterns to improve the existing code. Each time I see long if..then..else constructs, or switch statements to drive logic, I think of how much better the code would be if we allow encapsulation and use one of my favorite behavioral pattern… => the Strategy Pattern.

StrategyPatternA Strategy is a plan of action designed to achieve a specific goal

This is what this pattern will do for you: “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” (Gang of Four);

Specifies a set of classes, each representing a potential behaviour. Switching between those classes changes the application behavior. (the Strategy). This behavior can be selected at runtime (using polymorphism) or design time. It captures the abstraction in an interface, bury implementation details in derived classes.

When we have a set of similar algorithms and its need to switch between them in different parts of the application. With Strategy Pattern is possible to avoid ifs and ease maintenance;

Now, how can we digest that in code, now that you got the gist of the problem and want a better solution than your case statements.

This example I’ll be showing is a pure academic exercise:

The problem to solve is given a string as an input, create a parsing algorithm(s) that given a text stream identifies if the text complies with the following patterns. Angle brackets should have an opening and closing bracket and curly brackets should also have an opening and closing bracket, no matter how many characters are in the middle. These algorithms must be tested for performance.

<<>>{}  True
<<{>>}  False
<<<>    False
<<erertjgrh>>{sgsdgf} True


Continue reading I need to get rid of that switch statement. What is the Strategy Pattern?