js设计模式之状态模式

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>状态模式</title>

</head>

<body>

<button id="btn">开关</button>

<script>

    class OfflightState{

        constructor(light) {

            this.light = light;

        }

        //每个类都需要的这个方法,在不同的状态下按需要触发这个方法

        pressBtn(){

            this.light.setState(this.light.weekLightState);

            console.log("打开弱光")

        }

    }

    class WeekLightState{

        constructor(light) {

            this.light = light;

        }

        pressBtn(){

            this.light.setState(this.light.strongLightState);

            console.log("打开强光")

        }

    }

    class StrongLightState{

        constructor(light) {

            this.light = light;

        }

        pressBtn(){

            this.light.setState(this.light.offlightState);

            console.log("关闭灯光")

        }

    }

    class Light{

        constructor() {

            this.offlightState =new OfflightState(this);

            this.weekLightState =new WeekLightState(this);

            this.strongLightState =new StrongLightState(this);

            this.currentState =null;

        }

        setState(newState){

            this.currentState = newState;

        }

        init(){

            this.currentState=this.offlightState;

        }

    }

    let light =new Light();

    light.init();

    let btn =document.querySelector("#btn");

    btn.onclick=()=>{

        light.currentState.pressBtn();

    }

</script>

</body>

</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容