Strategy and State are behavioral design patterns that use composition and polymorphism, but they solve different problems. The Strategy Pattern focuses on selecting one algorithm or behavior from multiple alternatives, whereas the State Pattern allows an object to change its behavior automatically when its internal state changes.
Key Points: • Strategy Pattern is used to switch between different algorithms or business rules at runtime. • State Pattern changes an object's behavior based on its current state, making it appear as if the object's class has changed. • In Strategy, the client usually chooses the strategy; in State, transitions are typically managed by the state objects or the context itself.
Example: A payment application may use the Strategy Pattern to choose between Credit Card, UPI, or PayPal payment methods. A document workflow system may use the State Pattern where a document behaves differently in Draft, Review, and Published states.
Code Example:
interface PaymentStrategy {
void pay();
}
class CreditCardPayment
implements PaymentStrategy {
public void pay() {
System.out.println(
"Paid using Credit Card");
}
}
class UpiPayment
implements PaymentStrategy {
public void pay() {
System.out.println(
"Paid using UPI");
}
}
public class Main {
public static void main(String[] args) {
PaymentStrategy strategy =
new UpiPayment();
strategy.pay();
}
}Interview Tip: A concise interview answer is: The Strategy Pattern is used to select one behavior or algorithm from multiple alternatives, with the choice typically made by the client. The State Pattern is used when an object's behavior must change automatically based on its internal state. Strategy focuses on interchangeable algorithms, while State focuses on state-driven behavior changes.