package Observer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
//import java.lang.Exception;
//事件类,用来响应事件
class WakenUpEvent{
private long time;
private String loc;
private Child source;// 发出这件事的源对象
public WakenUpEvent(long time,String loc,Child source){
super();
this.time = time;
this.loc = loc;
this.source = source;
}
public long getTime(){
return time;
}
public void setTime(long time){
this.time = time;
}
public String getLoc(){
return loc;
}
public void setLoc(String loc){
this.loc = loc;
}
public Child getSource(){
return source;
}
public void setSource(Child source){
this.source = source;
}
}
//child类,并且在内部运行一个线程,激发事件的发生
class Child implements Runnable{
//使用数组创建监听类
private List<WakenUpListener> wakenUpListeners = new ArrayList<WakenUpListener>();
// boolean wakenUp = false;
public void addWakenUpListener(WakenUpListener l){
wakenUpListeners.add(l);
}
void wakenUp(){
for(int i=0; i<wakenUpListeners.size();i++){
WakenUpListener l = wakenUpListeners.get(i);
l.ActionToWakenUp(new WakenUpEvent(System.currentTimeMillis(),"bed",this));
}
}
public void run(){
try{
Thread.sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}
this.wakenUp();
}
}
//Dad监听者类继承WakenUpListener接口
class Dad implements WakenUpListener{
public void ActionToWakenUp(WakenUpEvent wue){
System.out.println("Dad feeded");
}
}
//Mom监听者类继承WakenUpListener接口
class Mom implements WakenUpListener{
public void ActionToWakenUp(WakenUpEvent wue){
System.out.println("Mom id here!");
}
}
class Dog implements WakenUpListener{
public void ActionToWakenUp(WakenUpEvent wue){
System.out.println("旺旺!!");
}
}
//监听者接口,当添加新的监听者时,不用修改原来的代码,只需要添加一个新的实现即可
interface WakenUpListener{
public void ActionToWakenUp(WakenUpEvent wue);
}
public class ChildDadFeed{
public static void main(String[] args){
Child c = new Child();
String[] observers = PropertyMgr.getProperty("observer").split(",");
for(String s:observers){
try {
//class.forName(s).newIntance()只能返回Object对象类型,需要强制转换成WakenUpListener类型
c.addWakenUpListener((WakenUpListener)(Class.forName(s).newInstance()));
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
new Thread(c).start();
}
}
class PropertyMgr{
//单例模式
//缓存,提高效率
private static Properties props = new Properties();
//静态初始化,静态初始化方法只执行一次,全程制度一次硬盘
//不足之处:
static {
try {
//读取配置文件
props.load(ChildDadFeed.class.getClassLoader().getResourceAsStream("Observer/observer.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key){
return props.getProperty(key);
}
}
/*class CryEvent{
}
abstract class Event{
}*/