What are the differences between the Object-Oriented Programming design patterns 'Strategy' and 'State'?
sobes.tech AI
Answer from AI
The "Strategy" and "State" patterns both use polymorphism to change an object's behavior, but they are applied in different contexts and solve different problems.
-
Strategy allows selecting an algorithm or behavior of an object at runtime. The main idea is to encapsulate different algorithms into separate classes and change them dynamically.
Example: sorting a list with different algorithms (quick, bubble, etc.).
-
State allows an object to change its behavior depending on its internal state, making it appear as if it has changed its class.
Example: an object that behaves differently in "On" and "Off" states.
Key differences:
| Aspect | Strategy | State |
|---|---|---|
| Goal | Choose algorithm/behavior | Change behavior depending on state |
| Context | External strategy choice | Internal object state |
| Behavior change | External switch | Automatic state switching |
Java example:
// Strategy
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Credit card payment: " + amount);
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("PayPal payment: " + amount);
}
}
class ShoppingCart {
private PaymentStrategy strategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void checkout(int amount) {
strategy.pay(amount);
}
}
// State
interface State {
void doAction(Context context);
}
class StartState implements State {
public void doAction(Context context) {
System.out.println("State: start");
context.setState(this);
}
}
class StopState implements State {
public void doAction(Context context) {
System.out.println("State: stop");
context.setState(this);
}
}
class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public State getState() {
return state;
}
}
Thus, the strategy focuses on choosing an algorithm, while the state manages the object's behavior depending on its internal state.