/** * 油箱油量小于等于定义的报警油量则报警 */ public class ObserveDemo { static class Car extends Observable { private Integer oil = new Integer(0); public void addOil(Integer oil) { this.oil += oil; } public void run() throws InterruptedException { System.out.println("汽车启动"); while (this.oil > 0) { oil--; Thread.sleep(1000); if (oil <= 5) { setChanged(); notifyObservers(oil); } } if(this.oil == 0){ stop(); } } public void stop() { System.out.println(toString() + "停止"); } public String toString() { return "你的汽车"; } } static class OilBoxObserver implements Observer { @Override public void update(Observable o, Object arg) { System.out.println(o.toString() + "该加油啦,油还剩" + (Integer) arg); } } public static void main(String[] args) throws InterruptedException { Car accord = new Car(); accord.addObserver(new OilBoxObserver()); accord.addOil(6); accord.run(); } }
汽车启动
你的汽车该加油啦,油还剩5
你的汽车该加油啦,油还剩4
你的汽车该加油啦,油还剩3
你的汽车该加油啦,油还剩2
你的汽车该加油啦,油还剩1
你的汽车该加油啦,油还剩0
你的汽车停止