JavaScript设计模式(状态模式)

1. 状态模式的定义

允许一个对象在其内部 状态改变时改变它的行为 ,对象看起来似乎修改了它的类。

class Battery{
    constructor() {
        this.amount='high';
    }
    show() {
        if (this.amount == 'high') {
            console.log('绿色');
            this.amount='middle';
        }else if (this.amount == 'middle') {
            console.log('黄色');
            this.amount='low';
        }else{
            console.log('红色');
        }
    }
}
let battery=new Battery();
battery.show();
battery.show();
battery.show();

2. 场景

2.1 点赞

let likeState={
    render(element) {
        element.innerHTML='赞👍';
    }
}
let likedState={
    render(element) {
        element.innerHTML='取消';
    }
}

class Button{
    constructor(container) {
        this.liked=false;
        this.state = likeState;
        this.element=document.createElement('button');
        container.appendChild(this.element);
        this.render();
    }
    setState(state) {
        this.state=state;
        this.render();
    }
    render() {
        this.state.render(this.element);
    }
}

let button=new Button(document.body);
button.element.addEventListener('click',() => {
    button.setState(button.liked? likeState:likedState);
    button.liked=!button.liked;
});

2.2 promise

class Promise{
    constructor(fn) {
        this.state='initial';
        this.successes=[];
        this.fails=[];
        let resolve=(data) => {
            this.state='fulfilled';
            this.successes.forEach(item=>item(data));
        }
        let reject=(error) => {
            this.state='failed';
            this.fails.forEach(item=>item(error));
        }
        fn(resolve,reject);
    }
    then(success,fail) {
        this.successes.push(success);
        this.fails.push(fail);
    }
}
let p=new Promise(function (resolve,reject) {
    setTimeout(function () {
        resolve(1);
    },1000);
});
p.then((data)=>console.log('成功'),error=>console.error('失败'));

2.3 有限状态机

//有限状态机 Finite-state machine
//var StateMachine=require('javascript-state-machine');
class StateMachine {
    constructor(options) {
        let { init, transitions, methods } = options;
        this.state = init;
        transitions.forEach(transition => {
            let { from, to, name } = transition;
            this[name] = function () {
                if (this.state == from) {
                    this.state = to;
                    let onMethod = 'on' + name.slice(0, 1).toUpperCase() + name.slice(1);
                    methods[onMethod] && methods[onMethod]();
                }
            }
        });
    }
}
var fsm = new StateMachine({
    init: 'solid',
    transitions: [{
        name: 'melt',
        from: 'solid',
        to: 'liquid'
    },
    {
        name: 'freeze',
        from: 'liquid',
        to: 'solid'
    },
    {
        name: 'vaporize',
        from: 'liquid',
        to: 'gas'
    },
    {
        name: 'condense',
        from: 'gas',
        to: 'liquid'
    }
    ],
    methods: {
        onMelt: function () {
            console.log('I melted')
        },
        onFreeze: function () {
            console.log('I froze')
        },
        onVaporize: function () {
            console.log('I vaporized')
        },
        onCondense: function () {
            console.log('I condensed')
        }
    }
});
fsm.melt();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容