package com.zhijun.test;
import java.util.ArrayList;
import java.util.List;
class WakenupEvent {
private long time;
private String location;
private Object source;
public WakenupEvent(long time, String location, Object source) {
super();
this.time = time;
this.location = location;
this.source = source;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Object getSource() {
return source;
}
public void setSource(Object source) {
this.source = source;
}
}
class Dad implements WakenUpListener {
public void ActionToWankenUp(WakenupEvent wakenupEvent) {
// TODO Auto-generated method stub
System.out.println("feed child");
}
}
class GrandFather implements WakenUpListener {
public void ActionToWankenUp(WakenupEvent wakenupEvent) {
// TODO Auto-generated method stub
System.out.println("hug child");
}
}
interface WakenUpListener {
public void ActionToWankenUp(WakenupEvent wakenupEvent);
}
class Child implements Runnable{
private List<WakenUpListener> wakenUpListeners = new ArrayList<WakenUpListener>();
private boolean wakenup = false;
public void addWakenUpListener(WakenUpListener l) {
wakenUpListeners.add(l);
}
void wakeup() {
wakenup = true;
for(int i=0; i<wakenUpListeners.size(); i++) {
WakenUpListener l = wakenUpListeners.get(i);
l.ActionToWankenUp(new WakenupEvent(System.currentTimeMillis(), "bed" , this));
}
}
public boolean isWakenup() {
return wakenup;
}
public void setWakenup(boolean wakenup) {
this.wakenup = wakenup;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.wakeup();
}
}
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Child c = new Child();
Dad d = new Dad();
GrandFather gf = new GrandFather();
c.addWakenUpListener(d);
c.addWakenUpListener(gf);
new Thread(c).start();
}
}
監聽機制Observers模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.