Want to Master Java Design Patterns?
Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!
Subscribe on YouTubeThe Real-World Dilemma: How to Travel to the Airport?
Imagine you need to reach an airport or a destination city. Depending on various factors such as budget, time availability, and urgency, you have multiple ways to travel:
- Own Car: Highly flexible, convenient, but requires fuel and parking fees.
- Taxi / Cab: On-demand, comfortable, but can be expensive during peak hours.
- City Bus: Economical and cost-effective, but takes longer due to frequent stops.
If you write a program that handles travel booking using hardcoded if-else conditions, adding a new travel mode like a metro train or shuttle service requires modifying existing code. The Strategy Design Pattern solves this cleanly.
Encapsulating Travel Options as Strategies
The Strategy pattern defines a family of algorithms or business rules, encapsulates each one into a dedicated class, and makes them interchangeable from the client’s perspective:
- Strategy Interface: Defines a common method (e.g.,
gotoAirport(String source, String destination)) implemented by every mode of travel. - Concrete Strategy Classes: Independent classes like
CarStrategy,TaxiStrategy, andBusStrategycontaining their respective journey details. - Context Class: Represents the traveler or booking system that holds a reference to a travel strategy and delegates the actual travel behavior to it.
Key Architectural Benefits
By decoupling the travel method from the traveler context:
- Adheres to Open/Closed Principle: You can add newer transit modes (like high-speed rail) without changing any existing classes.
- Dynamic Runtime Decision: The traveler can dynamically evaluate prices or traffic conditions and pick the best strategy at runtime.
- Testability: Each travel strategy can be tested independently in isolation.
Related Design Pattern Tutorials to Watch Next
Click here to watch in Youtube : https://www.youtube.com/watch?v=0PuxVZoQcKs
| Strategy Design pattern - Real Time Example [Travel] |
No comments:
Post a Comment