State Design Pattern - DeanHristov/ts-design-patterns-cheat-sheet GitHub Wiki
State Design Pattern
The State pattern is a behavioural design pattern that allows an object to alter its behavior when its internal state changes. The state pattern is used to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.
This pattern is very similar to the strategy design pattern. The main difference between them is that state pattern is aware of its state while in the strategy pattern its context doesn't know what strategy is used at the current point of time. A simple UML diagram can be seen here
A Great fit when:
- A clean way for an object to partially change its state at runtime
- An object should change its behavior when its internal state changes.
- State-specific behavior should be defined independently. That is, adding new states should not affect the behavior of existing states.
Simple implementation
The Context class
abstract class State {
protected ctx!: State;
protected readonly name: string;
protected constructor(name: string) {
this.name = name;
}
setState(ctx: State) {
this.ctx = ctx;
}
getState(): string {
return this.ctx.name;
}
abstract toggleState(): void;
}
The Concrete State 1
class OnState extends State {
constructor(name: string) {
super(name);
super.setState(this);
}
toggleState(): void {
super.setState(new OffState('OffState'));
}
}
The Concrete State 2
class OffState extends State {
constructor(name: string) {
super(name);
super.setState(this);
}
toggleState(): void {
super.setState(new OnState('OnState'));
}
}
Code in action
const stateOff: State = new OffState('OffState');
const stateOn: State = new OnState('OnState');
stateOff.toggleState();
stateOff.getState(); // OffState -> OnState
stateOn.toggleState();
stateOn.getState(); // OnState -> OffState
More info can be found on the wiki page.