方式三:更具備通用性,添加監聽事件(讓多個人同時監聽小孩醒來這個事件并作出相應動作,dad和mom就是觀察者)
class Dad implements WakeUpActionListener{
@Override
public void wakeUpAction(WakeUpEvent wakeUpEvent)
{
System.out.println("爸爸給小孩喂奶。。。");
}
}
class Mom implements WakeUpActionListener{
@Override
public void wakeUpAction(WakeUpEvent wakeUpEvent)
{
System.out.println("媽媽給小孩喂奶");
}
}
class WakeUpEvent{
}
interface WakeUpActionListener{
void wakeUpAction(WakeUpEvent wakeUpEvent);
}
class Child implements Runnable{
private List<WakeUpActionListener> listenerLists=new ArrayList<WakeUpActionListener>();
void addListener(WakeUpActionListener l){
listenerLists.add(l);
}
void wakeUp(){
System.out.println("醒來了");
for(WakeUpActionListener l:listenerLists){
l.wakeUpAction(new WakeUpEvent());
}
}
@Override
public void run()
{
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
wakeUp();
}
}
public class Test
{
public static void main(String[] args){
Dad d=new Dad();
Mom m=new Mom();
Child c=new Child();
c.addListener(d);
c.addListener(m);
new Thread(c).start();
}
}
用屬性檔案管理Observers
檔案名observer.properties,裡面内容:observers=ObserverMode.Dad,ObserverMode.Mom
将上面代碼部分的main函數換成以下
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException{
Child c=new Child();
Properties props=new Properties();
//如果檔案放在src下直接可以寫檔案名,如果放在包下寫上路徑
props.load(Test.class.getClassLoader().getResourceAsStream("ObserverMode/observer.properties"));
String[] observers=props.getProperty("observers").split(",");
for(String observer:observers){
c.addListener((WakeUpActionListener)Class.forName(observer).newInstance());
}
new Thread(c).start();
}
讀取硬碟換成單例模式:
public class Test
{
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException{
Child c=new Child();
//采用單例模式(優點:隻讀取一次硬碟;缺點:配置檔案更改不能立即生效)
//緩存讀取效率非常高
PropertiesManager props=new PropertiesManager();
String[] observers=props.getProperties("observers").split(",");
for(String observer:observers){
c.addListener((WakeUpActionListener)Class.forName(observer).newInstance());
}
new Thread(c).start();
}
}
class PropertiesManager{
private static Properties props=new Properties();
//靜态方法隻執行一次
static{
try
{
props.load(Test.class.getClassLoader().getResourceAsStream("ObserverMode/observer.properties"));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getProperties(String key){
return props.getProperty(key);
}
}