设计模式——状态模式

160 阅读1分钟

1. 状态模式概述

在状态模式中,类的行为是基于它的状态改变的。
状态模式允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。

(1) 适用情况

当代码中包含大量与对象状态有关的条件语句时,应该有限考虑状态模式。

(2) 优点

可以简化大量的条件判断,也可以很方便的增加新的状态。

(3) 缺点

状态模式会增加系统类和对象的个数。

2. 状态模式实例

使用状态模式来模拟电灯开关前后的状态。

public class Light {
    // 是否亮着
    private boolean light;

    public Light() {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                    if (light) {
                        System.out.println("灯火辉煌...");
                    } else {
                        System.out.println("一片漆黑...");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void turnOn() {
        this.light = true;
        System.out.println("灯开了。");
    }

    public void turnOff() {
        this.light = false;
        System.out.println("灯关了。");
    }
}
public class StateDemo {
    public static void main(String[] args) throws InterruptedException {
        Light light = new Light();
        Thread.sleep(5000);

        // 开灯
        light.turnOn();
        Thread.sleep(5000);

        // 关灯
        light.turnOff();
    }
}

运行结果:
image.png

3. 一些思考

上边的例子中,使用了一个线程来打印当前房间的状态,这个线程启动后一直都没有停止过。但是我们却通过开关灯,使得打印出了不同的结果,这就是状态模式。

参考引用

状态模式:www.runoob.com/design-patt…