Strategy Pattern

The Strategy pattern is one of the simpler Design patterns we might encounter in the world of design patterns. The strategy pattern is also very practical and could help us refactor and clean up some of our existing code.

The basic idea of a strategy pattern is for example when we have some calling code, which doesn’t need to know which strategy we are going to use. It basically can do its job by applying the strategy appropriately without caring at all what strategy is.

Let’s say we have this method:

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

In this method we have a switch statement where we switch on the CalculateOrderDiscount method with possible values StudentDiscount, LoyalDiscount, StudentDiscount.

One thing about using this technique is that is very possible that we’re going to get a new discount passed in on this method that we’re not actually coding for. For that scenario here we are throwing a “UnknownDiscountMethodException”.

Another red flag about this piece of code is that in most cases is not appropriate for the service to know what type of discount the customer fits under.

Let say for example we want to add a Christmas Discount, or National Student Day Discount. In all these cases we are going to have to open up this class and modify the CalculateOrderDiscount method, and that by definition breaks the Open Close Principle right away, which states that a class should be open for extension but closed for modification.

In this case our goal is to be able to calculate things independently of the  CalculateOrderDiscount service, and that’s where the Strategy Pattern comes in.

Here our Strategy interface declares a method that is going to be called by DiscountOrderCalculatorService to perform the calculation we’re interested in performing.

Then also we have concrete implementations of our Strategy interface for every strategy.

Finally, our Discount Order Calculator takes a strategy in its constructor as a constructor argument, which it holds as a member field to later using that strategy to perform its work.

Usage:

Another common way to implement the strategy pattern is using Property Injection,  Func, Actions or Delegates to push in our strategies.

Example:

Sample Code

LEAVE A REPLY

Please enter your comment!
Please enter your name here