diff --git "a/DesignPattern/20-\347\212\266\346\200\201\346\250\241\345\274\217.md" "b/DesignPattern/20-\347\212\266\346\200\201\346\250\241\345\274\217.md" index 1680c4c..b260874 100644 --- "a/DesignPattern/20-\347\212\266\346\200\201\346\250\241\345\274\217.md" +++ "b/DesignPattern/20-\347\212\266\346\200\201\346\250\241\345\274\217.md" @@ -424,3 +424,70 @@ func main() { } ``` +### Typescript + +``` typescript +interface IState { + handle(); +} + +class OnState implements IState { + handle() { + console.log("Light is ON"); + } +} + +class OffState implements IState { + handle() { + console.log("Light is OFF"); + } +} + +class BlinkState implements IState { + handle() { + console.log("Light is Blinking"); + } +} + +class StateContext { + private currentState: IState; + + constructor(state) { + this.currentState = state; + } + + setState(state: IState) { + this.currentState = state; + } + + getHandle() { + return this.currentState.handle(); + } +} + +// @ts-ignore +entry(5, (...args) => { + const classMap = { + ON: OnState, + OFF: OffState, + BLINK: BlinkState, + }; + + let state = new StateContext(new OffState()); + args.forEach((item) => { + state.setState(new classMap[item]()); + state.getHandle(); + }); +})("ON")("OFF")("BLINK")("OFF")("ON"); + +function entry(count: number, fn: (...args: any) => void) { + function dfs(...args) { + if (args.length < count) { + return (arg) => dfs(...args, arg); + } + + return fn(...args); + } + return dfs; +} +```