JavaScript设计模式之状态模式

发布于 / 学习

介绍

  • 一个对象有状态的变化
  • 每次状态变化都会触发一个逻辑
  • 不能总是用if..else控制

实例

  • 交通信号灯不同颜色的变化

UML类图

image

代码演示

    class State {
        constructor(color) {
            this.color = color
        }

        handle(context) {
            console.log('当前是' + this.color + '灯')
            context.setState(this)
        }
    }
    class Context{
        constructor() {
            this.state= null
        }
        getState(){
            return this.state
        }
        setState(state){
            this.state = state
        }

    }

    //test
    let context = new Context()
    let g = new State('g')
    let y = new State('y')
    let r = new State('r')

    //绿亮
    g.handle(context)
    context.getState()
    //黄亮
    y.handle()
    context.getState()
    //红亮
    r.handle()
    context.getState()

场景

  • 有限状态机
  • 简单的Promise

有限状态机制

  • 有限个状态,以及在这些状态之间的变化
  • 比如交通信号灯
  • javascript-state-machine
 npm install javascript-state-machine --save
    <script src="https://cdn.bootcss.com/javascript-state-machine/2.0.0/state-machine.min.js"></script>

    //初始化状态机模型
    let fsm = new StateMachine({
        init: '收藏',
        transactions: [
            {
                name: 'doStore',
                from: '收藏',
                to: '取消收藏'
            },
            {
                name: 'deleteStore',
                from: '取消收藏',
                to: '收藏'
            },
        ],
        methods: {
            //监听
            onDostore: function () {
                alert('收藏成功')
                updateText()
                //other ... ajax
            },
            onDeleteStore: function () {
                alert('取消收藏成功')
                updateText()
                //other ... ajax
            }
        }
    })

    let btn = document.getElementById('btn1')

    btn.onclick(function () {
        if(fsm.is('收藏')){
            fsm.doStore()
        }else{
            fsm.deleteStore()
        }
    })

    function updateText() {
        btn.innerText = fsm.state
    }

实现状态变化的Promise

let fsm = new StateMachine({
        init: 'pending',
        transactions: [
            {
                name: 'resolve',
                from: 'pendinf',
                to: 'fullfilled'
            },
            {
                name: 'reject',
                from: 'pending',
                to: 'rejected'
            },
        ],
        methods: {
            //监听
            //state 当前状态机实例
            // data fsm.resolve(xxx) 传递的参数
            onResolve: function (state,data) {
                data.successList.forEach(fn=>fn())
            },
            onReject: function (state,data) {
                data.failList.forEach(fn=>fn())
            }
        }
    })

    class MyPromise{
        constructor(fn) {
            this.successList = []
            this.failList = []
            fn(()=>{
                //fsm状态机
                fsm.resolve(this)
            },()=>{
                fsm.reject(this)
            })
        }
        then(successFn,failFn){
            this.successList.push(successFn)
            this.failList.push(failFn)
        }

    }

代码

https://github.com/ahwgs/design-pattern-learning/tree/master/11.JavaScript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8B%E7%8A%B6%E6%80%81%E6%A8%A1%E5%BC%8F

本文采用 CC BY-NC-SA 3.0 Unported 协议进行许可
本文链接: https://www.ahwgs.cn/javascriptshejimoshizhizhuangtaimoshi.html