From b318565e8469cd112c17efc2dcbaec7ee133d482 Mon Sep 17 00:00:00 2001 From: caojunjie <1301239018@qq.com> Date: Mon, 4 Nov 2024 19:19:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(typescript):=2020=20=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...66\346\200\201\346\250\241\345\274\217.md" | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) 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; +} +```