interface State {
doAction(context: Context): void;
}
class StartState implements State {
public doAction(context: Context): void {
console.log("Player is in start state");
context.setState(this);
}
public toString(): string {
return "Start State";
}
}
class StopState implements State {
public doAction(context: Context): void {
console.log("Player is in stop state");
context.setState(this);
}
public toString(): string {
return "Stop State";
}
}
class Context {
private state!: State;
constructor() {
this.state;
}
public setState(state: State): void {
this.state = state;
}
public getState(): State {
return this.state;
}
}
class StatePatternDemo {
constructor(args: string[]) {
let context: Context = new Context();
let startState: StartState = new StartState();
startState.doAction(context);
console.log(context.getState().toString());
let stopState: StopState = new StopState();
stopState.doAction(context);
console.log(context.getState().toString());
}
}