State
Let an object change its behaviour when its internal state changes.
Use it when
An object's behaviour depends on its state and you have large state-based conditionals.
/**
* State: an order behaves differently depending on where it is in its life.
*
* Real-world scenario: an online shop. ship() and cancel() mean different things
* for a pending order, a shipped order and a cancelled one. Instead of if/else
* checks on a status field in every method, each state is a class that handles
* the actions its own way and decides which state comes next. Adding a state
* (say, Delivered) means adding a class, not editing every method.
*/
// State: what every order state must handle.
interface OrderState {
readonly name: string;
ship(order: Order): void;
cancel(order: Order): void;
}
// Concrete states: each one handles the actions in its own way.
class Pending implements OrderState {
readonly name = "Pending";
ship(order: Order): void {
console.log(" Packed and handed to the courier");
order.state = new Shipped();
}
cancel(order: Order): void {
console.log(" Cancelled, full refund issued");
order.state = new Cancelled();
}
}
// States that never change the order can leave the parameter out.
class Shipped implements OrderState {
readonly name = "Shipped";
ship(): void {
console.log(" Already on its way");
}
cancel(): void {
console.log(" Too late to cancel: please return it after delivery");
}
}
class Cancelled implements OrderState {
readonly name = "Cancelled";
ship(): void {
console.log(" Can't ship a cancelled order");
}
cancel(): void {
console.log(" Already cancelled");
}
}
// Context: delegates every action to its current state. No if/else on status.
class Order {
readonly orderId: string;
state: OrderState = new Pending();
constructor(orderId: string) {
this.orderId = orderId;
}
ship(): void {
console.log(`${this.orderId} [${this.state.name}] ship()`);
this.state.ship(this);
}
cancel(): void {
console.log(`${this.orderId} [${this.state.name}] cancel()`);
this.state.cancel(this);
}
}
function clientCode(): void {
const first = new Order("ORD-1");
first.ship();
first.cancel();
const second = new Order("ORD-2");
second.cancel();
second.ship();
}
clientCode();
// Output:
// ORD-1 [Pending] ship()
// Packed and handed to the courier
// ORD-1 [Shipped] cancel()
// Too late to cancel: please return it after delivery
// ORD-2 [Pending] cancel()
// Cancelled, full refund issued
// ORD-2 [Cancelled] ship()
// Can't ship a cancelled orderHow it works
| Role | Classes | What it does |
|---|---|---|
| Context | Order | Holds the current state and hands every action to it; no if/else on status |
| State | OrderState | Interface with ship() and cancel() |
| Concrete states | Pending, Shipped, Cancelled | Each handles the actions its own way and decides the next state |
| Client | clientCode() | Calls the same actions on orders in different states |