Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions DesignPattern/20-状态模式.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
```