设计模式之观察者模式(二)

来源:互联网 发布:莫知其丑 编辑:程序博客网 时间:2024/05/09 19:14

接着上篇改进方案1。

下面是方案2:

package DesighMethod02;public class Test02 {/** * @param args */public static void main(String[] args) {Dad d = new Dad();child c = new child(d);new Thread(c).start();}}class child implements Runnable{private Dad d;private boolean wakenup = false; //默认是睡着的状态int time;public child(Dad d) {this.d=d;}public void wakeUp(Dad d){wakenup = true;d.feed(this);}public boolean isWakenup() {return wakenup;}public void setWakenup(boolean wakenup) {this.wakenup = wakenup;}public int getTime() {return time;}public void setTime(int time) {this.time = time;}@Overridepublic void run() {try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}this.wakeUp(d);}}class Dad implements Runnable{private child c;public void feed (child c2){System.out.println("feed child");}public void run() {while(!c.isWakenup()){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}feed(c);}}

这个方案仍有缺陷,缺乏扩展性。

原创粉丝点击