Want to Master Java Design Patterns?
Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!
Subscribe on YouTubeReal-World Scenario: Choosing a Travel Mode
When planning a trip, a traveler can reach their destination using different modes of transportation: Car, Bus, Train, or Flight. Each option has its own cost, travel duration, and route logic.
In software design, modeling this with hardcoded conditions creates rigid, messy code. By applying the Strategy Design Pattern, each travel option becomes an interchangeable strategy class that can be switched dynamically at runtime.
Why Use the Strategy Pattern Here?
- Extensibility: Need to add bike or ferry travel later? Add a new class without modifying existing travel logic.
- Clean Code: Eliminates complicated
switch-caseor conditional branches inside your booking engine. - Runtime Selection: Users can change their travel preference dynamically based on budget or schedule.
Components of the Architecture
- TravelStrategy (Interface): Declares common methods like
travel(String source, String destination). - Concrete Strategies: Classes such as
CarTravelStrategy,BusTravelStrategy, orFlightTravelStrategy. - Traveler / Context: Holds a reference to the selected
TravelStrategyand executes the journey.
Java Code Walkthrough
1. Define the Common Strategy Interface:
public interface TravelStrategy {
void gotoAirport(String source, String destination);
}
2. Implement Concrete Strategies:
public class TaxiTravelStrategy implements TravelStrategy {
@Override
public void gotoAirport(String source, String destination) {
System.out.println("Traveling from " + source + " to " + destination + " by Taxi.");
}
}
3. Build the Travel Context:
public class TravelContext {
private TravelStrategy travelStrategy;
public void setTravelStrategy(TravelStrategy travelStrategy) {
this.travelStrategy = travelStrategy;
}
public void travel(String source, String destination) {
travelStrategy.gotoAirport(source, destination);
}
}
Related Design Pattern Tutorials to Watch Next
Click here to watch in Youtube : https://www.youtube.com/watch?v=37zZUuAuk7w
Click the below Image to Enlarge
| Strategy Design pattern - Implementation [Travel] |
| Strategy Design pattern - Implementation [Travel] - Class Diagram |
TravelStrategy.java
public interface TravelStrategy
{
public void gotoAirport();
}
AutoTravelStrategy.java
public class AutoTravelStrategy implements TravelStrategy
{
public void gotoAirport()
{
System.out.println("Traveler is going to Airport by Auto and will be charged 600 Rs");
}
}
BusTravelStrategy.java
public class BusTravelStrategy implements TravelStrategy
{
public void gotoAirport()
{
System.out.println("Traveler is going to Airport by bus and will be charged 200 Rs");
}
}
TaxiTravelStrategy.java
public class TaxiTravelStrategy implements TravelStrategy
{
public void gotoAirport()
{
System.out.println("Traveler is going to Airport by Taxi and will be charged 1000 Rs");
}
}
TrainTravelStrategy.java
public class TrainTravelStrategy implements TravelStrategy
{
public void gotoAirport()
{
System.out.println("Traveler is going to Airport by Train and will be charged 300 Rs");
}
}
TravelContext.java
public class TravelContext
{
private TravelStrategy travelStrategy;
// Client will set what TravelStrategy to use by calling this method
public void setTravelStrategy(TravelStrategy strategy)
{
this.travelStrategy = strategy;
}
public TravelStrategy getTravelStrategy()
{
return travelStrategy;
}
public void gotoAirport()
{
travelStrategy.gotoAirport();
}
}
Traveler.java
import java.util.Scanner;
public class Traveler
{
public static void main( String[] args )
{
System.out.println("Please enter Travel Type : 'Bus' or 'Train' or 'Taxi' or 'Auto' ");
Scanner scanner = new Scanner(System.in);
String travelType = scanner.next();
System.out.println("Travel type is : " + travelType);
TravelContext ctx = null;
ctx = new TravelContext();
if( "Bus".equalsIgnoreCase(travelType) )
{
ctx.setTravelStrategy(new BusTravelStrategy());
}
else if("Train".equalsIgnoreCase(travelType))
{
ctx.setTravelStrategy(new TrainTravelStrategy());
}
else if("Taxi".equalsIgnoreCase(travelType))
{
ctx.setTravelStrategy(new TaxiTravelStrategy());
}
else if("Auto".equalsIgnoreCase(travelType))
{
ctx.setTravelStrategy(new AutoTravelStrategy());
}
System.out.println("Travel context has : "+ctx.getTravelStrategy());
ctx.gotoAirport();
}
}
Output
Please enter Travel Type : 'Bus' or 'Train' or 'Taxi' or 'Auto'
bus
Travel type is : bus
Travel context has : BusTravelStrategy@1e4cbc4
Traveler is going to Airport by bus and will be charged 200 Rs
Please enter Travel Type : 'Bus' or 'Train' or 'Taxi' or 'Auto'
train
Travel type is : train
Travel context has : TrainTravelStrategy@578ceb
Traveler is going to Airport by Train and will be charged 300 Rs
car rent carngo rentalcar rentalcar
ReplyDelete