一、概述
1.目标:读取properties文件改成单例模式
二、代码
1.Test.java
class WakenUpEvent{ private long time;
private String location;
private Child source; public WakenUpEvent(long time, String location, Child 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 Child getSource() {
return source;
} public void setSource(Child source) {
this.source = source;
} } class Child implements Runnable { private List<WakenUpListener> wakenUpListeners = new ArrayList<WakenUpListener>(); public void addWakenUpListener(WakenUpListener wul){
wakenUpListeners.add(wul);
}
public void wakeUp(){
for(int i = 0; i < wakenUpListeners.size(); i++){
WakenUpListener l = wakenUpListeners.get(i);
l.actionToWakenUp(new WakenUpEvent(System.currentTimeMillis(), "bed", this));
}
} @Override
public void run() {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
wakeUp();
}
} interface WakenUpListener {
public void actionToWakenUp(WakenUpEvent e);
} class Dad implements WakenUpListener { public void actionToWakenUp(WakenUpEvent e) {
System.out.println("Fedd the child");
} } class GrandFather implements WakenUpListener { public void actionToWakenUp(WakenUpEvent e) {
System.out.println("抱孩子");
} } class PropertiesMgr{ private static Properties props = new Properties(); //只加载一次,但如果properties有更新,它不会反馈
static {
try {
props.load(Test.class.getClassLoader().getResourceAsStream("com/tong/observer/observer.properties"));
} catch (Exception e) {
e.printStackTrace();
}
} public static String getProperty(String key){
return props.getProperty(key);
}
}
public class Test { public static void main(String[] args) { Child c = new Child(); String [] observers = PropertiesMgr.getProperty("observers").split(","); for(String s : observers){
try {
c.addWakenUpListener((WakenUpListener)Class.forName(s).newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
new Thread(c).start();
}
}
三、运行结果