What is the State pattern?

Answer

The State pattern allows an object to alter its behavior when its internal state changes. The object appears to change its class. Instead of large switch/if-else based on state, each state is its own class. Vending machine example: interface VendingMachineState { void insertCoin(VendingMachine machine); void selectProduct(VendingMachine machine, String product); void dispense(VendingMachine machine); } class IdleState implements VendingMachineState { public void insertCoin(VendingMachine machine) { machine.setBalance(machine.getBalance() + 1); System.out.println("Coin accepted. Balance: $" + machine.getBalance()); machine.setState(new CoinInsertedState()); } public void selectProduct(VendingMachine machine, String product) { System.out.println("Please insert a coin first."); } public void dispense(VendingMachine machine) { System.out.println("Please insert a coin first."); } } class CoinInsertedState implements VendingMachineState { public void insertCoin(VendingMachine machine) { System.out.println("Coin already inserted. Balance: $" + machine.getBalance()); } public void selectProduct(VendingMachine machine, String product) { if (machine.hasProduct(product)) { machine.setSelectedProduct(product); machine.setState(new ProductSelectedState()); System.out.println("Selected: " + product); } else { System.out.println("Product out of stock."); } } public void dispense(VendingMachine machine) { System.out.println("Please select a product first."); } } class VendingMachine { private VendingMachineState currentState = new IdleState(); private double balance = 0; private String selectedProduct; // ... state + getters/setters public void setState(VendingMachineState state) { this.currentState = state; } public void insertCoin() { currentState.insertCoin(this); } public void selectProduct(String product) { currentState.selectProduct(this, product); } }. Benefits: state-specific behavior in state classes (no large conditionals), easy to add new states, cleaner code. Real uses: traffic lights, UI (enabled/disabled/loading), order status, network connections, game characters.