Strategy (Design Pattern)

Strategy – that’s a very complex thing, isn’t it? Let’s not worry about what’s going to be a corporate strategy or war strategy or anything. Given that we are software engineers, let’s focus on “Strategy” design pattern and it’s advantages.

What is a Strategy Design Pattern?

This is a behavioral design pattern which enables clients to choose the algorithm to be used at run-time. An algorithm is a set of steps which are taken on input data to produce the output value. Based on the need of the application, there could be different algorithms possible to be used. A very basic approach could be using conditional statements inside the implementation and let client pass the values for conditions. A better approach is to separate the implementations in different classes and have them implement a single common interface.

W3sDesign Strategy Design Pattern UML
Let’s take an example. You are writing a file compression utility which can compress a file using Zip, Rar, or GZip algorithms. In such case, user can provide the compression type to be used along with a set of files. The strategy pattern implementation internally chooses which algorithm to use to produce the compressed file output.

Another example could be implementing discount offers in a restaurant or for a website. One can have a discount strategy for happy hour billing and normal billing. Or you can have higher discounts for premium customers, one time discount for new customers and a standard discount for rest. All such different algorithms could be implemented using Strategy design pattern.

Advantages

Strategy pattern allows to configure the strategy to be used and the implementation of the strategy is outside the base class. This gives flexibility to the implementor to implement the required algorithm without making any changes to the interface or the base class.

Related Links

Related Keywords

Design Patterns, Behavioral Design Pattern, Gang Of Four

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.