Imagine an Order in an e-commerce microservice. The rules for “canceling” an order change depending on its state. If it is Pending, you just delete it. If it is Shipped, you have to trigger a reverse-logistics return process.
The rules of a method (behavior) changing on the state
- The State interface
public interface OrderState {
void cancelOrder();
}
- The different lifecycle behaviors
public class PendingState implements OrderState {
public void cancelOrder() { System.out.println("Order deleted from DB."); }
}
public class ShippedState implements OrderState {
public void cancelOrder() { System.out.println("Too late to delete. Initiating return process."); }
}
- The Context (The object doing the delegating)
public class Order {
private OrderState currentState;
public Order() {
this.currentState = new PendingState(); // Starts here
}
public void shipOrder() {
this.currentState = new ShippedState(); // State transitions!
}
public void cancel() {
// The result of this method completely changes based on the internal state
currentState.cancelOrder();
}
}