Strategy Design Pattern

Strategy Design Pattern is one of the behavioural design patterns. This pattern helps to bring different strategies to the table, which means implementing different strategies for a task For example, payment services have different strategies (options) on e-commerce platforms e.g. credit card, net banking, UPI, pay later, wallets, etc. Some more examples are Logging levels, Sorting Algorithms, etc.

The object-oriented design principle says “code for interfaces rather than implementation,” meaning the interface defines a task’s behaviour and different classes implement the interface. So, having different implementations of a task means having different strategies, and using interfaces to provide implementation instead of calling direct implementation. Check below example:

List<?> list = new ArrayList<?>();
list = new LinkedList<>();


The same “list” variable can be used to call different implementations based on requirements, whether you want to fetch (ArrayList) or update (LinkedList) the list. Similarly, calling any interface method doesn’t tie you with any particular implementation/business Logic and we can leverage the benefit of better or improved implementation over time.

The strategy design pattern is based upon open-closed design principles. Open for extension but closed for modification, which means we can add any new strategy implementation without modifying the existing ones.  Like other design patterns, strategy design pattern also add more classes but it’s worth it because it gives you the power of scalability. Scalability is the most important aspect of code design because it helps you organize your code and provides much-needed flexibility.

Intent: Strategy Design Pattern’s sole intent is to provide a mechanism to run the different algorithms based on input provided by the client.

Structure:

  • Strategy Interface: Defines the common methods for all concrete implementations for example a compare method from the Comparator interface in Java. (What is supposed to do? like “Pay”)
  • Concrete Strategies: Implementation in different classes. It is decided on runtime. (How exactly was it implemented? like “Credit Card Pay”)
  • Client: The client selects the strategy and passes it to the context.
  • Context: Configure the context with the required strategy at the runtime in the Context class and later context delegates the work to the selected concrete strategy.


One Comment

  1. Nicely explained, short and crisp.

Leave a Reply

Your email address will not be published. Required fields are marked *