状态模式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>状态模式</title>
</head>
<body>
    <script>
        // 状态父类
        class LightState {
            constructor(light) {
                this.light = light
            }

            buttonWasPressed() {
                throw new Error('父类的buttonWasPressed方法必须被重写')
            }
        }

        // 状态子类
        class OffLightState extends LightState {
            buttonWasPressed() {
                console.log('弱光') // offLightState对应的行为
                this.light.setState(this.light.weakLightState) // 切换状态到 weakLightState
            }
        }

        class WeakLightState extends LightState {
            buttonWasPressed() {
                console.log('强光') // weakLightState对应的行为
                this.light.setState(this.light.strongLightState) // 切换状态到 strongLightState
            }
        }

        class StrongLightState extends LightState {
            buttonWasPressed() {
                console.log('超强光') // strongLightState对应的行为
                this.light.setState(this.light.superStrongLightState) // 切换状态到 superStrongLightState
            }
        }

        class SuperStrongLightState extends LightState {
            buttonWasPressed() {
                console.log('关灯') // superStrongLightState对应的行为
                this.light.setState(this.light.offLightState) // 切换状态到 offLightState
            }
        }

        // 灯类
        class Light {
            constructor() {
                this.offLightState = new OffLightState(this)
                this.weakLightState = new WeakLightState(this)
                this.strongLightState = new StrongLightState(this)
                this.superStrongLightState = new SuperStrongLightState(this)
                this.button = null
            }

            init() {
                const button = document.createElement('button')
                this.button = document.body.appendChild(button)
                this.button.innerHTML = '开关'

                this.currState = this.offLightState // 设置当前状态
                this.button.onclick = () => this.currState.buttonWasPressed() // 将请求委托给当前的状态对象
            }

            setState(newState) {
                this.currState = newState
            }
        }

        const light = new Light()
        light.init()
    </script>
</body>
</html>

状态模式

版权声明:程序员胖胖胖虎阿 发表于 2023年8月31日 下午8:32。
转载请注明:状态模式 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...