观察者模式弊端:虽然观察者模式将依赖倒转原则做的很好,但是还是依赖了观察者的抽象接口,但是有些场景并不能抽象出观察者,比如引用的jar或者观察者做出的反应并不是同一类操作。
java委托机制:利用反射机制实现动态代理。
实现:定义事件类,封装被代理的类及要代理的方法和方法的调用,定义事件管理类,定义增加事件类对象和调用所有事件类代理方法。定义统治者类,聚合事件管理器,定义抽象方法增加事件和通知所有观察者类的方法(即调用所有代理方法)。最后定义观察者类,将观察者类的响应方法添加到事件管理其中实现动态代理。
/**
* 事件类
* @author liuhao
*
*/
public class Event {
private Object object;
private String methodName;
private Object[] params;
private Class[] paramTypes;
public Event(Object object,String method,Object...args)
{
this.object = object;
this.methodName = method;
this.params = args;
contractParamTypes(this.params);
}
private void contractParamTypes(Object[] params)
{
this.paramTypes = new Class[params.length];
for (int i=0;i<params.length;i++)
{
this.paramTypes[i] = params[i].getClass();
}
}
public void invoke() throws Exception
{
Method method = object.getClass().getMethod(this.methodName, this.paramTypes);//判断是否存在这个函数
if (null == method)
{
return;
}
method.invoke(this.object, this.params);//利用反射机制调用函数
}
}
import java.util.ArrayList;
import java.util.List;
public class EventHandler {
private List<Event> events;
public EventHandler()
{
events = new ArrayList<Event>();
}
public void addEvent(Object object, String methodName, Object...args)
{
events.add(new Event(object, methodName, args));
}
public void notifyX() throws Exception
{
for (Event event : events)
{
event.invoke();
}
}
}
/**
* 通知者抽象类
* @author liuhao
*
*/
public abstract class Notifier {
private EventHandler eventHandler = new EventHandler();
public EventHandler getEventHandler()
{
return eventHandler;
}
public void setEventHandler(EventHandler eventHandler)
{
this.eventHandler = eventHandler;
}
public abstract void addListener(Object object,String methodName, Object...args);
public abstract void notifyX();
}
/**
* 通知者实现类
* @author liuhao
*
*/
public class ConcreteNotifier extends Notifier{
@Override
public void addListener(Object object, String methodName, Object... args) {
this.getEventHandler().addEvent(object, methodName, args);
}
@Override
public void notifyX() {
try {
this.getEventHandler().notifyX();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 观察者,不需要抽象
* @author liuhao
*
*/
public class WatchingTVListener {
public WatchingTVListener()
{
System.out.println("watching TV");
}
public void stopWatchingTV(Date date)
{
System.out.println("stop watching" + date);
}
}
import java.util.Date;
public class Test {
public static void main (String[] args)
{
Notifier goodNotifier = new ConcreteNotifier();
WatchingTVListener watchingTVListener = new WatchingTVListener();
goodNotifier.addListener(watchingTVListener, "stopWatchingTV", new Date());
goodNotifier.notifyX();
}
}
结果: