• 技术文章 >Web开发 >JavaScript

    js状态模式是什么

    小妮浅浅小妮浅浅2021-08-20 09:25:28原创2390

    说明

    1、关键是区分事物内部的状态,事物内部状态往往会带来事物的行为改变。

    即允许对象在内部状态发生改变时改变它的行为。

    2、状态模式就是封装状态,允许一个对象在其内部状态改变时改变它的行为,我们之前一般都是封装行为。

    实例

    // 红灯
    class RedLight {
        constructor (state) {
            this.state = state;
        }
        light () {
            console.log('turn to red light');
            this.state.setState(this.state.greenLight)
        }
    }
    // 绿灯
    class greenLight {
        constructor (state) {
            this.state = state;
        }
        light () {
            console.log('turn to green light');
            this.state.setState(this.state.yellowLight)
        }
    }
    // 黄灯
    class yellowLight {
        constructor (state) {
            this.state = state;
        }
        light () {
            console.log('turn to yellow light');
            this.state.setState(this.state.redLight)
        }
    }
    class State {
        constructor () {
            this.redLight = new RedLight(this)
            this.greenLight = new greenLight(this)
            this.yellowLight = new yellowLight(this)
            this.setState(this.redLight) // 初始化为红灯
        }
        setState (state) {
            this.currState = state;
        }
    }
    const state = new State();
    state.currState.light() // turn to red light
    setInterval(() => {
        state.currState.light() // 每隔3秒依次打印红灯、绿灯、黄灯
    }, 3000)

    以上就是js状态模式的介绍,希望对大家有所帮助。更多js学习指路:js教程

    推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

    专题推荐:js状态模式
    品易云
    上一篇:js迭代器模式是什么 下一篇:javascript字符串的语法介绍

    相关文章推荐

    • jsp注释格式• json格式化工具有哪些• nodejs和js的区别• java基础中JRE、JDK、JVM是什么?• java基础:编译运行过程如何实现?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网