Java Behavioral Design Patterns – Strategy Design Pattern

The Strategy Design Pattern is one of the behavioral design patterns, it is also called as policy pattern that enables selecting an algorithm at runtime according to requirement.

In this pattern, we define multiple algorithms or strategies and client chooses one as per requirement. This algorithm is then passed as a parameter to processing units. The key points for Strategy Pattern are:

  • Create multiple algorithms and form a family of them.
  • Encapsulate each member of algorithm family
  • The algorithms must be interchangeable within that family.

<Here are ALL other Java Design Patterns, explained in detail with examples>

Strategy Design Pattern by Example

For our understanding and demonstrate this pattern, we will take an example of Travel Booking System. In this system, the customer has 3 different options or strategies to choose from. Based upon his selection the fare for his travel is calculated.

We have 3 booking strategies Bus, Train, and Car.

Booking Strategy Interface

The above interface defines a simple method to get the fare. This interface will be implemented by actual strategies.

Car Booking Strategy

Train Booking Strategy

Bus Booking Strategy

Now let’s define the actual Customer class. This class will have a variable holder for strategy interface. This strategy will be set in the booking flow and fare is calculated as per that.

Main Class

Below is our main class that will create customer and set booking strategy.

Output

In the above output, you can see the fares are calculated as per the strategy is chosen during the booking flow.

Conclusion

So that’s all about strategy pattern, the same Strategy object can also be purposefully shared between different Context objects. However, the shared Strategy object should not maintain states across invocations. At the same time, the application must be alert of all the strategies to select the right one for the right situation and as per requirement.

You can download the code from our GitHub repository:

Download from Git

 

<Here are ALL other Java Design Patterns, explained in detail with examples>

Add a Comment

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