Refactor if/elseif/elseif using Strategy Design Pattern

Sandesh Gaonkar
AIA Singapore Technology Blog
2 min readNov 8, 2022

Strategy Design pattern enables an algorithm’s behavior to be selected at runtime. The pattern

· Defines a family of algorithms

· Encapsulates each algorithm

· Makes the algorithms interchangeable within that family.

Below is the architecture of the strategy design pattern where the client will communicate with context. The context will hold the reference to the strategy object which reflects another design principle “program to an interface and not an implementation”.

Let’s check how we can refactor old style if else statements using below scenario.

The problem with this design is it will always affect the business logic implementation whenever we need to add or modify any mode of transport.
Let's refactor the tightly coupled code using a strategy design patterns.

Strategy Interface and its implementation
Context Object holding Strategy Reference

The client code will be as below

Pros :
1. Adding a new strategy will never disturb any previous code.
2. Removal/Refactoring of any previous strategy is flexible.
3. Easy to test single units.

--

--