opencodez

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:

xHere are ALL other Java Design Patterns, explained in detail with examplesx

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

public interface BookingStrategy {
	public double getFare();
}

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

Car Booking Strategy

public class CarBookingStrategy implements BookingStrategy {

	@Override
	public double getFare() {
		return 12.5;
	}
	
	@Override
	public String toString(){
		return "CarBookingStrategy";
	}
}

Train Booking Strategy

public class TrainBookingStrategy implements BookingStrategy {

	@Override
	public double getFare() {
		return 8.5;
	}

	@Override
	public String toString(){
		return "TrainBookingStrategy";
	}	
}

Bus Booking Strategy

public class BusBookingStrategy implements BookingStrategy {

	@Override
	public double getFare() {
		return 5.5;
	}

	@Override
	public String toString(){
		return "BusBookingStrategy";
	}
}

Now letxs 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.

public class Customer {
	
	private BookingStrategy bookingStrategy;
	
	public Customer(BookingStrategy bs) {
		this.bookingStrategy = bs;
	}
	
	public double calculateFare(int numOfPassangeres) {
		double fare = numOfPassangeres * getBookingStrategy().getFare();
		System.out.println("Calculating fares using " + getBookingStrategy());
		return fare;
	}

	public BookingStrategy getBookingStrategy() {
		return bookingStrategy;
	}

	public void setBookingStrategy(BookingStrategy bookingStrategy) {
		this.bookingStrategy = bookingStrategy;
	}

}

Main Class

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

public class StrategyPatternDemo {

	public static void main(String[] args) {
		
		//CarBooking Strategy
		Customer cust = new Customer(new CarBookingStrategy());
		double fare = cust.calculateFare(5);
		System.out.println(fare);
		
		//TrainBooking Strategy
		cust.setBookingStrategy(new TrainBookingStrategy());
		fare = cust.calculateFare(5);
		System.out.println(fare);
		
		//TrainBooking Strategy
		cust.setBookingStrategy(new BusBookingStrategy());
		fare = cust.calculateFare(5);
		System.out.println(fare);

	}

}

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

x

xHere are ALL other Java Design Patterns, explained in detail with examplesx