interface FSMNode {
enter(): void;
exit(): void;
tick(interval: number): void;
release?(): void; // 可选方法,用于释放资源
}
class StateA implements FSMNode {
enter() {
console.log("Entered State A");
}
exit() {
console.log("Exited State A");
}
tick(interval: number) {
console.log(`State A ticked with interval ${interval}`);
}
// 假设StateA不需要释放资源
}
class StateB implements FSMNode {
enter() {
console.log("Entered State B");
}
exit() {
console.log("Exited State B");
}
tick(interval: number) {
console.log(`State B ticked with interval ${interval}`);
}
// 假设StateB也不需要释放资源
}
class FSMMachine {
private currentState: FSMNode | null = null;
private states: { [id: string]: FSMNode } = {};
addState(id: string, state: FSMNode): void {
if (this.states[id]) {
throw new Error(`State with ID '${id}' already exists.`);
}
this.states[id] = state;
}
setInitialState(id: string): void {
if (!this.states[id]) {
throw new Error(`State with ID '${id}' does not exist.`);
}
if (this.currentState) {
this.currentState.exit();
}
this.currentState = this.states[id];
this.currentState.enter();
}
changeState(newId: string): void {
if (!this.states[newId]) {
throw new Error(`State with ID '${newId}' does not exist.`);
}
if (this.currentState) {
this.currentState.exit();
}
this.currentState = this.states[newId];
this.currentState.enter();
}
tick(interval: number): void {
if (this.currentState) {
this.currentState.tick(interval);
}
}
// 假设FSMMachine不需要一个单独的release方法,因为状态可以在需要时单独释放
}
// 创建状态实例
const stateA = new StateA();
const stateB = new StateB();
// 创建FSMMachine实例并添加状态
const fsm = new FSMMachine();
fsm.addState("A", stateA);
fsm.addState("B", stateB);
// 设置初始状态
fsm.setInitialState("A");
// 更改状态
fsm.changeState("A");
// 调用tick方法
fsm.tick(1000); // 假设这是以毫秒为单位的间隔
// 如果需要,可以回到状态A
fsm.changeState("A");
fsm.tick(500); // 再次调用tick,这次是在状态A中