定义
状态模式,是一种行为设计模式,它允许将在内部状态改变时改变它的行为,对象会看起来好像修改了它的类。
这种模式主要是通过将状态相关的行为封装在独立的状态类中,然后在上下文对象中维护当前状态的引用,以此来实现状态和行为的分离。
UML 类图
typescript 实现
1. 定义状态接口
interface State {
handle(context: Context): void;
}
2. 创建具体状态类
class ConcreteStateA implements State {
public handle(context: Context): void {
console.log("ConcreteStateA handles request.");
context.changeState(new ConcreteStateB());
}
}
class ConcreteStateB implements State {
public handle(context: Context): void {
console.log("ConcreteStateB handles request.");
context.changeState(new ConcreteStateA());
}
}
3. 创建上下文类
class Context {
private state: State;
constructor(state: State) {
this.state = state;
}
public changeState(state: State): void {
console.log(`Context: Change to ${state.constructor.name}`);
this.state = state;
this.state.handle(this);
}
}
4. 使用示例
const context = new Context(new ConcreteStateA());
context.changeState(new ConcreteStateB());
通用实现
无