Skip to main content

状态模式/State Pattern

什么是状态模式

在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。

在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。

面向对象例子:

class BasicState{
constructor(control) {
this.control = control;
}

btnWasPressed(dom) {
throw new Error('Basic function must be rewrite');
}

stopWasPressed(dom) {
throw new Error('Basic function must be rewrite');
}
}

class StopState extends BasicState{
constructor(control) {
super(control);
}

btnWasPressed(dom) {
console.log('starting play');
dom.innerText = 'pause';
this.control.setState(this.control.playState);
}

stopWasPressed(dom) {
console.log('stoped');
dom.innerText = 'start';
this.control.setState(this.control.stopState);
}
}

class PlayState extends BasicState{
constructor(control) {
super(control);
}

btnWasPressed(dom) {
console.log('paused');
dom.innerText = 'start';
this.control.setState(this.control.pauseState);
}

stopWasPressed(dom) {
console.log('stoped');
dom.innerText = 'start';
this.control.setState(this.control.stopState);
}
}



class PauseState extends BasicState{
constructor(control) {
super(control);
}

btnWasPressed(dom) {
console.log('starting play');
dom.innerText = 'pause';
this.control.setState(this.control.playState);
}

stopWasPressed(dom) {
console.log('stoped');
dom.innerText = 'start';
this.control.setState(this.control.stopState);
}
}



export default class Control{
constructor() {
this.stopState = new StopState(this);
this.playState = new PlayState(this);
this.pauseState = new PauseState(this);
this.currentState = this.stopState;
}

setState(state) {
this.currentState = state;
}
}