Strategy Design Pattern — Beginner Class Notes
1. Class ki shuruaat kaise karein?
Students se pehle ye question poochho:
Maan lo hume Delhi se Jaipur jaana hai. Hum kaun-kaun se tareekon se ja sakte hain?
Students ke possible answers:
Car
Bus
Train
Flight
Ab unse poochho:
Destination same hai, lekin travel karne ka tareeka same hai ya alag?
Answer:
Tareeka alag hai.
Isi concept ko software me Strategy Pattern kehte hain.
2. Strategy Pattern kya hai?
Strategy Pattern ka meaning hai:
Jab ek kaam ko karne ke multiple tareeke ya algorithms hon, tab har tareeke ko ek alag class me rakhna aur runtime par required tareeka choose karna.
Simple formula:
Same kaam
+
Multiple tareeke
=
Strategy Pattern
Example:
Travel karna ek kaam hai.
Car se travel karna → Ek strategy
Bus se travel karna → Dusri strategy
Train se travel karna → Teesri strategy
Flight se travel karna → Chauthi strategy
3. Real-life example
Maan lo Amit ko Delhi se Jaipur jaana hai.
Uske paas options hain:
Car
Bus
Train
Flight
Har option ka objective same hai:
Delhi se Jaipur pahunchna
Lekin har option ka behavior alag hai:
Car → Flexible hai, lekin fuel lagega
Bus → Sasti hai, lekin time zyada lag sakta hai
Train → Comfortable hai
Flight → Fast hai, lekin expensive hai
Amit apni requirement ke according kisi bhi strategy ko choose kar sakta hai.
Kam budget → Bus
Comfort chahiye → Train
Jaldi pahunchna → Flight
Flexible route → Car
4. Strategy Pattern ka main purpose
Strategy Pattern ka purpose sirf if-else hatana nahi hai.
Iska real purpose hai:
Changing behavior ko main class se separate karna.
Strategy Pattern se:
Har algorithm alag class me hota hai.
New algorithm add karna easy hota hai.
Existing code kam modify hota hai.
Testing easy hoti hai.
Code flexible aur maintainable hota hai.
5. Strategy Pattern ke bina design
Sabse pehle wrong approach dikhate hain.
class TravelService {
public void travel(String mode) {
if (mode.equals("CAR")) {
System.out.println("Travelling by car");
} else if (mode.equals("BUS")) {
System.out.println("Travelling by bus");
} else if (mode.equals("TRAIN")) {
System.out.println("Travelling by train");
} else if (mode.equals("FLIGHT")) {
System.out.println("Travelling by flight");
}
}
}
Usage:
public class Main {
public static void main(String[] args) {
TravelService service = new TravelService();
service.travel("TRAIN");
}
}
Output:
Travelling by train
6. Is code me problem kya hai?
Starting me code simple lag raha hai, lekin future me problems hongi.
Problem 1: Large if-else
Kal naye travel modes aa gaye:
Bike
Metro
Auto
Ship
Helicopter
Har mode ke liye naya else-if add karna padega.
else if (mode.equals("BIKE")) {
}
else if (mode.equals("METRO")) {
}
Class badi aur difficult hoti jayegi.
Problem 2: Existing class baar-baar modify hogi
Jab bhi new travel mode add hoga, hume TravelService class change karni padegi.
Ye Open-Closed Principle ko violate karta hai.
Open-Closed Principle kehta hai:
Class extension ke liye open honi chahiye, lekin modification ke liye closed honi chahiye.
Problem 3: TravelService ko sab kuch pata hai
TravelService ko pata hai:
Car kaise travel karti hai
Bus kaise travel karti hai
Train kaise travel karti hai
Flight kaise travel karti hai
Ek class ke paas bahut saari responsibilities aa gayi hain.
Problem 4: Testing difficult hogi
Sirf Train ka logic test karne ke liye bhi hume poori TravelService test karni padegi.
7. Strategy Pattern ka solution
Strategy Pattern me hum har travel behavior ko alag class me rakhenge.
Iske teen main components hote hain:
1. Strategy Interface
2. Concrete Strategies
3. Context Class
Architecture:
TravelStrategy
|
-----------------------------------
| | |
CarStrategy BusStrategy TrainStrategy
|
Traveller
Context
8. Step 1: Strategy Interface
Sabhi travel modes ke liye ek common contract banayenge.
interface TravelStrategy {
void travel(String source, String destination);
}
Interface ye rule define karta hai:
Har travel strategy ko
travel()method implement karna hoga.
Interface ko ye nahi pata travel kaise hoga.
Usse bas operation ka naam pata hai.
9. Step 2: Concrete Strategies
Car Strategy
class CarTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Car"
);
}
}
Bus Strategy
class BusTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Bus"
);
}
}
Train Strategy
class TrainTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Train"
);
}
}
Flight Strategy
class FlightTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Flight"
);
}
}
Har class sirf apne travel behavior ko handle kar rahi hai.
10. Step 3: Context Class
Context wo class hoti hai jo strategy ko use karti hai.
class Traveller {
private TravelStrategy travelStrategy;
public Traveller(TravelStrategy travelStrategy) {
this.travelStrategy = travelStrategy;
}
public void startJourney(
String source,
String destination
) {
travelStrategy.travel(source, destination);
}
}
Yahan Traveller ko ye nahi pata ki actual strategy:
Car hai
Bus hai
Train hai
Flight hai
Traveller sirf interface par depend karta hai:
private TravelStrategy travelStrategy;
Ye important concept hai:
Program to an interface, not an implementation.
11. Client code
public class Main {
public static void main(String[] args) {
TravelStrategy strategy =
new TrainTravelStrategy();
Traveller traveller =
new Traveller(strategy);
traveller.startJourney(
"Delhi",
"Jaipur"
);
}
}
Output:
Travelling from Delhi to Jaipur by Train
12. Internally flow kaise chal raha hai?
Main class
|
| TrainTravelStrategy object banaya
v
Traveller
|
| startJourney() call hua
v
travelStrategy.travel()
|
| Runtime object TrainTravelStrategy hai
v
Train ka implementation execute hua
Same method call hai:
travelStrategy.travel(source, destination);
Lekin result runtime object decide karta hai.
Isi ko runtime polymorphism kehte hain.
13. Strategy runtime par change karna
Maan lo pehle user Train choose karta hai.
Baad me ticket available nahi milti, to user Bus choose kar leta hai.
Context me setter add karenge:
class Traveller {
private TravelStrategy travelStrategy;
public Traveller(TravelStrategy travelStrategy) {
this.travelStrategy = travelStrategy;
}
public void setTravelStrategy(
TravelStrategy travelStrategy
) {
this.travelStrategy = travelStrategy;
}
public void startJourney(
String source,
String destination
) {
travelStrategy.travel(source, destination);
}
}
Usage:
public class Main {
public static void main(String[] args) {
Traveller traveller =
new Traveller(
new TrainTravelStrategy()
);
traveller.startJourney(
"Delhi",
"Jaipur"
);
traveller.setTravelStrategy(
new BusTravelStrategy()
);
traveller.startJourney(
"Delhi",
"Jaipur"
);
}
}
Output:
Travelling from Delhi to Jaipur by Train
Travelling from Delhi to Jaipur by Bus
Important point:
Traveller class change nahi hui.
Sirf Strategy object replace hua.
Yahi Strategy Pattern ki main power hai.
14. Complete Java Code
interface TravelStrategy {
void travel(String source, String destination);
}
class CarTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Car"
);
}
}
class BusTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Bus"
);
}
}
class TrainTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Train"
);
}
}
class FlightTravelStrategy implements TravelStrategy {
@Override
public void travel(String source, String destination) {
System.out.println(
"Travelling from " + source +
" to " + destination +
" by Flight"
);
}
}
class Traveller {
private TravelStrategy travelStrategy;
public Traveller(TravelStrategy travelStrategy) {
this.travelStrategy = travelStrategy;
}
public void setTravelStrategy(
TravelStrategy travelStrategy
) {
if (travelStrategy == null) {
throw new IllegalArgumentException(
"Travel strategy cannot be null"
);
}
this.travelStrategy = travelStrategy;
}
public void startJourney(
String source,
String destination
) {
if (source == null || destination == null) {
throw new IllegalArgumentException(
"Source and destination are required"
);
}
travelStrategy.travel(source, destination);
}
}
public class Main {
public static void main(String[] args) {
Traveller traveller =
new Traveller(
new CarTravelStrategy()
);
traveller.startJourney(
"Delhi",
"Jaipur"
);
traveller.setTravelStrategy(
new TrainTravelStrategy()
);
traveller.startJourney(
"Delhi",
"Mumbai"
);
traveller.setTravelStrategy(
new FlightTravelStrategy()
);
traveller.startJourney(
"Delhi",
"Bangalore"
);
}
}
Output:
Travelling from Delhi to Jaipur by Car
Travelling from Delhi to Mumbai by Train
Travelling from Delhi to Bangalore by Flight
15. Class diagram ko kaise explain karein?
<<interface>>
TravelStrategy
|
|
--------------------------------
| | |
CarStrategy BusStrategy TrainStrategy
|
FlightStrategy
Traveller
-------------------------------
- travelStrategy: TravelStrategy
-------------------------------
+ startJourney()
+ setTravelStrategy()
Relationship:
Traveller HAS-A TravelStrategy
Ye inheritance nahi, composition hai.
Traveller IS-A TravelStrategy ❌
Traveller HAS-A TravelStrategy ✅
16. Strategy Pattern me kaun kya hai?
Travel example me:
Strategy Interface
→ TravelStrategy
Concrete Strategies
→ CarTravelStrategy
→ BusTravelStrategy
→ TrainTravelStrategy
→ FlightTravelStrategy
Context
→ Traveller
Client
→ Main class
17. Ek aur practical example: Payment System
Travel example samjhane ke baad Payment example se relate karo.
Ek e-commerce application me payment ke multiple methods ho sakte hain:
UPI
Card
Cash
Wallet
Net Banking
Same task:
Payment karna
Different strategies:
UPI se payment
Card se payment
Wallet se payment
Payment Strategy Interface
interface PaymentStrategy {
void pay(double amount);
}
UPI Strategy
class UpiPaymentStrategy
implements PaymentStrategy {
private final String upiId;
public UpiPaymentStrategy(String upiId) {
this.upiId = upiId;
}
@Override
public void pay(double amount) {
System.out.println(
"₹" + amount +
" paid using UPI ID: " + upiId
);
}
}
Card Strategy
class CardPaymentStrategy
implements PaymentStrategy {
private final String cardNumber;
public CardPaymentStrategy(
String cardNumber
) {
this.cardNumber = cardNumber;
}
@Override
public void pay(double amount) {
String lastFourDigits =
cardNumber.substring(
cardNumber.length() - 4
);
System.out.println(
"₹" + amount +
" paid using Card ending with " +
lastFourDigits
);
}
}
Cash Strategy
class CashPaymentStrategy
implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println(
"₹" + amount +
" will be paid using Cash"
);
}
}
Context
class CheckoutService {
private PaymentStrategy paymentStrategy;
public CheckoutService(
PaymentStrategy paymentStrategy
) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(double amount) {
System.out.println("Order validated");
paymentStrategy.pay(amount);
System.out.println("Order confirmed");
}
}
Usage
public class Main {
public static void main(String[] args) {
PaymentStrategy paymentStrategy =
new UpiPaymentStrategy(
"amit@upi"
);
CheckoutService checkoutService =
new CheckoutService(
paymentStrategy
);
checkoutService.checkout(2500);
}
}
Output:
Order validated
₹2500.0 paid using UPI ID: amit@upi
Order confirmed
18. Context aur Strategy ki responsibilities
Students ko ye difference clearly samjhao.
CheckoutService ka kaam
Order validate karna
Payment trigger karna
Order confirm karna
PaymentStrategy ka kaam
Actual payment algorithm execute karna
CheckoutService ko ye nahi pata payment:
UPI se hui
Card se hui
Cash se hui
Wo common interface ko call karta hai:
paymentStrategy.pay(amount);
19. Strategy Pattern aur SOLID Principles
Single Responsibility Principle
Har class ka ek clear kaam hai.
UpiPaymentStrategy
→ Sirf UPI payment handle karegi.
CardPaymentStrategy
→ Sirf Card payment handle karegi.
CheckoutService
→ Checkout workflow manage karegi.
Open-Closed Principle
Kal Net Banking add karni ho:
class NetBankingPaymentStrategy
implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println(
"₹" + amount +
" paid using Net Banking"
);
}
}
Existing classes modify nahi karni padi.
Sirf nayi class add hui.
Dependency Inversion Principle
Wrong:
class CheckoutService {
private UpiPaymentStrategy paymentStrategy;
}
Is design me CheckoutService sirf UPI ke saath kaam kar sakti hai.
Correct:
class CheckoutService {
private PaymentStrategy paymentStrategy;
}
Ab CheckoutService kisi bhi payment strategy ke saath kaam kar sakti hai.
20. Dependency Injection aur Strategy Pattern
CheckoutService service =
new CheckoutService(
new UpiPaymentStrategy("amit@upi")
);
Yahan do concepts use ho rahe hain.
Strategy Pattern
Multiple payment behaviors ko interchangeable banaya gaya.
UPI
Card
Cash
Dependency Injection
Strategy object ko CheckoutService ke andar create nahi kiya.
Outside se provide kiya gaya.
Strategy Pattern
→ Kaunsa behavior available hai?
Dependency Injection
→ Behavior ka object class ko kaise milega?
Dono same nahi hain, lekin saath use hote hain.
21. Strategy Pattern aur Polymorphism
PaymentStrategy strategy;
Ye reference different objects hold kar sakta hai:
strategy = new UpiPaymentStrategy("amit@upi");
Ya:
strategy = new CardPaymentStrategy(
"1234567812345678"
);
Call same rahega:
strategy.pay(1000);
Lekin implementation runtime object decide karega.
Ye runtime polymorphism hai.
22. Important classroom question
Students se poochho:
Strategy Pattern ke baad bhi strategy choose karne ke liye if-else nahi lagega?
Answer:
Kabhi-kabhi strategy select karne ke liye if-else ya switch lag sakta hai.
PaymentStrategy strategy;
if (paymentType.equals("UPI")) {
strategy = new UpiPaymentStrategy("amit@upi");
} else {
strategy = new CashPaymentStrategy();
}
Lekin difference samjho.
Pehle if-else ke andar complete business logic tha:
if (type.equals("UPI")) {
// UPI validation
// UPI server connection
// payment
}
Strategy Pattern ke baad if-else sirf object choose kar raha hai:
strategy = new UpiPaymentStrategy("amit@upi");
Actual algorithm separate class me hai.
Selection logic ko Factory Pattern me bhi move kiya ja sakta hai.
23. Strategy vs Factory Pattern
Factory Pattern
→ Object create karta hai.
Strategy Pattern
→ Chosen object ka algorithm execute karta hai.
Example:
PaymentStrategy strategy =
PaymentStrategyFactory.create("UPI");
Yahan:
PaymentStrategyFactory.create()
→ Factory Pattern
strategy.pay()
→ Strategy Pattern
24. Strategy vs State Pattern
Dono ka code structure similar lag sakta hai, lekin purpose different hai.
Strategy Pattern
Client behavior choose karta hai.
User ne UPI choose kiya.
User ne Card choose kiya.
State Pattern
Object ki current state behavior decide karti hai.
Order Created
↓
Order Paid
↓
Order Shipped
↓
Order Delivered
Difference:
Strategy
→ Multiple algorithms me se selection.
State
→ Current state ke according behavior change.
Examples:
Payment method choose karna
→ Strategy Pattern
Order CREATED se SHIPPED hona
→ State Pattern
25. Strategy Pattern kab use karein?
Strategy Pattern use karo jab:
Condition 1
Ek kaam karne ke multiple tareeke hon.
Payment
Sorting
Discount
Travel
Notification
Route finding
Compression
Condition 2
Algorithm runtime par choose karna ho.
User Card ya UPI choose kare.
Condition 3
Bada if-else ya switch different behaviors handle kar raha ho.
Condition 4
Algorithms independently test karne hon.
Condition 5
Future me naye algorithms add hone ki possibility ho.
26. Strategy Pattern kab nahi use karna chahiye?
Har if-else par Strategy Pattern mat lagao.
Example:
if (age >= 18) {
System.out.println("Eligible");
}
Iske liye alag Strategy class banana overengineering hoga.
Strategy avoid karo jab:
Sirf ek algorithm ho.
Logic bahut chhota ho.
Future me behavior change hone ki possibility na ho.
Pattern use karne se unnecessary classes badh rahi hon.
Good design ka matlab maximum patterns use karna nahi hota.
Good design ka matlab appropriate jagah par correct pattern use karna hota hai.
27. Advantages
Strategy Pattern ke fayde:
1. Large if-else reduce hota hai.
2. Algorithms separate classes me rehte hain.
3. New strategy add karna easy hota hai.
4. Runtime par strategy change kar sakte hain.
5. Code testable hota hai.
6. Code maintainable hota hai.
7. Open-Closed Principle follow hota hai.
8. Composition aur polymorphism ka use hota hai.
28. Disadvantages
Strategy Pattern ke kuch drawbacks bhi hain:
1. Classes ki sankhya badh sakti hai.
2. Client ko available strategies ki knowledge honi chahiye.
3. Chhote logic ke liye pattern overengineering ho sakta hai.
4. Strategy selection ke liye Factory ya Resolver chahiye ho sakta hai.
29. Common mistakes
Mistake 1: Context ke andar concrete strategy banana
Wrong:
class CheckoutService {
private PaymentStrategy strategy;
public CheckoutService(String type) {
if (type.equals("UPI")) {
strategy =
new UpiPaymentStrategy("amit@upi");
}
}
}
Context ab strategy selection bhi kar raha hai.
Better:
PaymentStrategy strategy =
new UpiPaymentStrategy("amit@upi");
CheckoutService service =
new CheckoutService(strategy);
Mistake 2: Strategy ke andar unrelated work daalna
Wrong:
class UpiPaymentStrategy {
public void pay() {
// Payment
// Save order
// Send email
// Update inventory
}
}
UPI strategy ka kaam sirf payment karna hai.
Order save, email aur inventory alag responsibilities hain.
Mistake 3: Bahut badi interface banana
Wrong:
interface PaymentStrategy {
void pay();
void refund();
void sendEmail();
void generateInvoice();
}
Har payment method refund support nahi karega.
Interface small aur focused honi chahiye:
interface PaymentStrategy {
void pay(double amount);
}
30. Interview definition
Interview me Strategy Pattern ko is tarah define kar sakte hain:
Strategy Pattern ek behavioral design pattern hai jo multiple related algorithms ko separate classes me encapsulate karta hai, unhe ek common interface provide karta hai aur client ko runtime par required algorithm choose karne ki facility deta hai.
Simple Hinglish definition:
Ek kaam ko karne ke multiple tareekon ko alag-alag classes me rakhna aur runtime par required tareeka select karna Strategy Pattern hai.
31. Strategy Pattern identify karne ka shortcut
Question me ye words aaye:
Multiple ways
Different algorithms
Runtime selection
User choice
Replaceable behavior
Different calculation rules
Different providers
To Strategy Pattern consider karo.
Examples:
Payment method
→ Strategy
Discount calculation
→ Strategy
Google Maps route
→ Strategy
Notification channel
→ Strategy
Sorting algorithm
→ Strategy
File compression
→ Strategy
Game winning logic
→ Strategy
32. Students ke liye classroom exercise
Question
Ek notification system design karo.
Notification ke methods:
Email
SMS
WhatsApp
Push Notification
Expected interface:
interface NotificationStrategy {
void send(String message);
}
Expected concrete strategies:
EmailNotificationStrategy
SmsNotificationStrategy
WhatsAppNotificationStrategy
PushNotificationStrategy
Expected context:
NotificationService
Students ko 10–15 minutes code karne do.
33. Quick MCQs
Question 1
Strategy Pattern kis category ka pattern hai?
A. Creational B. Structural C. Behavioral D. Architectural
Correct answer:
C. Behavioral
Question 2
Strategy Pattern ka main purpose kya hai?
A. Object clone karna B. Multiple algorithms ko interchangeable banana C. Database connect karna D. Singleton object banana
Correct answer:
B. Multiple algorithms ko interchangeable banana
Question 3
Strategy Pattern generally kis principle ko promote karta hai?
A. Composition over inheritance B. Global variables C. Tight coupling D. Static methods
Correct answer:
A. Composition over inheritance
Question 4
Strategy Pattern me Context kis par depend karta hai?
A. Concrete strategy B. Strategy interface C. Database D. Main class
Correct answer:
B. Strategy interface
Question 5
Payment method choose karna kis pattern ka example hai?
A. State B. Observer C. Strategy D. Singleton
Correct answer:
C. Strategy
34. Viva questions
Students se ye questions poochho:
1. Strategy Pattern kya solve karta hai?
2. Strategy interface ka role kya hai?
3. Concrete Strategy kya hoti hai?
4. Context class kya karti hai?
5. Runtime par strategy kaise change hoti hai?
6. Strategy Pattern me polymorphism kaise use hota hai?
7. Strategy aur State Pattern me kya difference hai?
8. Strategy aur Factory Pattern me kya difference hai?
9. Strategy Pattern Open-Closed Principle kaise follow karta hai?
10. Har if-else par Strategy Pattern kyon nahi lagana chahiye?
35. Final class summary
Class ke end me ye lines repeat karo:
Same kaam ke multiple tareeke
→ Strategy Pattern
Har tareeka separate class
→ Concrete Strategy
Sabke liye common contract
→ Strategy Interface
Strategy ko use karne wali class
→ Context
Strategy ko choose karne wala
→ Client
Runtime par strategy replace
→ Flexibility
Interface ke through execution
→ Polymorphism
Final one-line explanation:
Strategy Pattern changing algorithms ko separate classes me encapsulate karta hai, common interface provide karta hai aur context ko runtime par required algorithm use karne deta hai.
Sabse important point:
Strategy Pattern ka real purpose sirf if-else remove karna nahi hai. Iska purpose changing behavior ko main business class se separate karke interchangeable, maintainable aur testable banana hai.