白筱汐

想都是问题,做都是答案

0%

JavaScript设计模式——状态模式

介绍

状态模式,它允许对象在内部状态改变时改变其行为。该模式将对象的行为包装成一个状态对象,再利用上下文(Context)来管理状态对象。 当上下文对象内部状态改变时,它会自动切换所依赖的状态对象,并且使用当前状态对象的行为

主要概念:

  1. 上下文(Context):负责维护对象的状态,并将请求委托给当前状态对象来处理。
  2. 抽象状态(State): 定义状态对象接口,以实现所有具体状态类的共同行为。
  3. 具体状态(ConcreteState):实现抽象状态接口,并提供不同的行为实现来完成请求。

ts代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 抽象状态类
abstract class State {
abstract handle(context: Context): void;
}

// 具体状态类:开始状态
class StartState extends State {
handle(context: Context) {
context.setState(new ProcessingState());
}
}

// 具体状态类:处理中状态
class ProcessingState extends State {
handle(context: Context) {
context.setState(new Completedstate());
}
}

// 具体状态类:完成状态
class Completedstate extends State {
handle() {
console.log('任务完成');
}
}

// 上下文类
class Context {
private state: State;

constructor() {
this.state = new StartState();
}

setState(state: State) {
console.log(
`当前状态由 ${this.state.constructor.name} 变为 ${state.constructor.name}`
);
this.state = state;
}

request() {
this.state.handle(this);
}
}

const ctx = new Context();
ctx.request(); // 当前状态由 StartState 变为 ProcessingState
ctx.request(); // 当前状态由 ProcessingState 变为 Completedstate
ctx.request(); // 任务完成