一句话总结
变化时通知我
别名
观察者模式又叫做发布-订阅模式,源-监听器模式
内容
当一个对象发生变化时,所有依赖他的对象会自动获取通知并做响应,主要目的是解耦。
场景
监听器、日志收集、短信通知、邮件通知
类图
代码示例
public class Event {
//事件源
private Object source;
//通知目标
private Object target;
//回调
private Method callback;
//触发
private String trigger;
private long time;
public Event(Object target, Method callback) {
this.target = target;
this.callback = callback;
}
public Object getSource() {
return source;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
public Method getCallback() {
return callback;
}
public void setCallback(Method callback) {
this.callback = callback;
}
public String getTrigger() {
return trigger;
}
@Override
public String toString() {
return "Event{" +
"\n\tsource=" + source + ",\n" +
"\ttarget=" + target + ",\n" +
"\tcallback=" + callback + ",\n" +
"\ttrigger='" + trigger + '\'' + "\n" +
'}';
}
public long getTime() {
return time;
}
Event setTime(long time) {
this.time = time;
return this;
}
Event setSource(Object source) {
this.source = source;
return this;
}
Event setTrigger(String trigger) {
this.trigger = trigger;
return this;
}
}
public class EventLisenter {
//Map相当于是一个注册器
protected Map<Enum,Event> events = new HashMap<Enum,Event>();
public void addLisenter(Enum eventType,Object target,Method callback){
//注册事件
//用反射调用这个方法
events.put(eventType,new Event(target,callback));
}
private void trigger(Event e){
e.setSource(this);
e.setTime(System.currentTimeMillis());
try {
e.getCallback().invoke(e.getTarget(),e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
protected void trigger(Enum call){
if(!this.events.containsKey(call)){ return ;}
trigger(this.events.get(call).setTrigger(call.toString()));
}
}
public enum SubjectEventType {
ON_ADD,
ON_RMOVE,
ON_EDIT,
ON_QUERY;
}
public class Observer {
public void advice(Event e){
System.out.println("=========触发事件,打印日志========\n" + e);
}
}
public class Subject extends EventLisenter{
public void add(){
System.out.println("调用添加的方法");
trigger(SubjectEventType.ON_ADD);
}
public void remove(){
System.out.println("调用删除的方法");
trigger(SubjectEventType.ON_RMOVE);
}
}
public class ObserverTest {
public static void main(String[] args) {
try{
Observer observer = new Observer();
Method advice = Observer.class.getMethod("advice", new Class<?>[]{Event.class});
Subject subject = new Subject();
subject.addLisenter(SubjectEventType.ON_ADD,observer,advice);
subject.addLisenter(SubjectEventType.ON_EDIT,observer,advice);
subject.addLisenter(SubjectEventType.ON_RMOVE,observer,advice);
subject.addLisenter(SubjectEventType.ON_QUERY,observer,advice);
subject.add();
}catch (Exception e){
e.printStackTrace();
}
}
}
执行结果