Strategy Design Pattern in Java

by | Oct 6, 2020 | Java

Home » Java » Strategy Design Pattern in Java

Strategy Design Pattern is an important part of Behavioural Designs Patterns in JAVA. The word ‘strategy’ becomes key to be able to understand how this pattern works. A problem can be solved by applying various strategies. Even if all strategies deliver the required output, it is imperative that the most efficient strategy is used such that the code is efficient. It is this pattern that works out the best strategy to encounter a certain problem.

Definition

As defined in the Gang of Four book, the Strategy Pattern ‘lays before users a set of encapsulated algorithms that can be swapped to carry out a specific behaviour’. There are several algorithms (strategies) that are well defined. It is upto the client request and the parameter list that will decide which algorithm will process it.

Structure

In object-oriented programming, each strategy is given the shape of an individual object. These strategies will apply to a reference object that is conventionally called a context object. The context object will behave as per the strategy chosen.

Example and Code

The following example is a loan management service where each type of loan will have a separate interest rate.

//The interface defining the Loan company
public interface Loan {
BigDecimal interestAmt(BigDecimal int);
}
//This class will define the interest rates for dofferent types of loans
public static class StudentLoan implements Loan {
@override
public BigDecimal interestAmt(final BigDecimal int) {
return int*1.1;                                                   //10% interest rate
}
}
public static class HouseLoan implements Loan {
@override
public BigDecimal interestAmt(final BigDecimal int) {
return int*1.25;                                                                //12.5% interest rate
}
}
//Implementing the strategy
Loan obj1 = new StudentLoan();
BigDecimal totalAmt = StudentLoan.interestAmt(//Value of principal);
.
.
.
//Repeat the same method and object call for other types of loans.

When to use the Strategy Design Pattern?

The Strategy pattern is generally used when there is a group of algorithms in hands to tackle a certain type of request or service. In this pattern, clients will have full freedom to choose a particular strategy moving forward. New algorithms can also be added to the interface by encapsulating the existing ones.

Author

0 Comments

Submit a Comment

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

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

Author