标签:
观察者模式是对象的行为模式,又叫发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
public class:
package com.observer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class MainTest {
public static void main(String[] args) {
Child c = new Child();
Properties props = new Properties();
try {
props.load(MainTest.class.getClassLoader().getResourceAsStream("observer.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String []observers = props.getProperty("observers").split(",");
for(String s : observers) {
try {
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();
}
}
抽象主题角色类
package com.observer;
import java.util.ArrayList;
import java.util.List;
/**
* 一个主题对象,主题对象状态发生变化时,会通知所有观察者
* @author IRON_MAN
*
*/
class Child implements Runnable {
/**
* 把所有观察者对象的引用保存在List中
*/
private List<WakenUpListener> wakenUpListeners = new ArrayList<WakenUpListener>();
/**
* 保存添加观察者对象
* @param wakenUpListener
*/
public void addWakenUpListener(WakenUpListener wakenUpListener) {
wakenUpListeners.add(wakenUpListener);
}
/**
* 通知所有观察者对象
*/
void wakeUp() {
System.out.println("wake");
for(int i = 0; i < wakenUpListeners.size(); i++) {
WakenUpListener wakenUpListener = wakenUpListeners.get(i);
wakenUpListener.actionToWakenUp(new WakenUpEvent(System.currentTimeMillis(), "a", this));
}
}
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.wakeUp();
}
}
抽象观察者角色类
package com.observer;
public interface WakenUpListener {
public void actionToWakenUp(WakenUpEvent wakeUpEvent);
}
具体观察者角色类
package com.observer;
/**
* 观察者Dad,可自动更新自己
* @author IRON_MAN
*
*/
class Dad implements WakenUpListener {
public void actionToWakenUp(WakenUpEvent wakenUpEvent) {
System.out.println("feed");
}
}
package com.observer;
/**
* 观察者GrandFather
* @author IRON_MAN
*
*/
class GrandFather implements WakenUpListener {
public void actionToWakenUp(WakenUpEvent wakeUpEvent) {
System.out.println("hug");
}
}
抽象事件类
package com.observer;
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 String getLoc() {
return loc;
}
public Child getSource() {
return source;
}
public void setTime(long time) {
this.time = time;
}
public void setLoc(String loc) {
this.loc = loc;
}
public void setSource(Child source) {
this.source = source;
}
}
配置properties文件
observers=com.observer.Dad,com.observer.GrandFather
标签:
原文地址:http://blog.csdn.net/jyh1314/article/details/51353196