下面通过个例子来说明下:
先来定义一个接口,jdk的动态代理基于接口来创建代理类,不能基于类的原因是java不支持多重继承,而代理类都会继承Proxy类(个人理解).
[java]
/**
* Subject
*
* @author Kevin Fan
* @since 2013-9-13 下午2:43:33
*/
public interface Subject {
void pub(String key, String content);
String sub(String key);
}
再来一个具体的实现,在代理模式中可以叫它的实例可以叫target,这个是真正执行操作的对象
[java]
/**
* SimpleSubject
*
* @author Kevin Fan
* @since 2013-9-13 下午2:45:03
*/
public class SimpleSubject implements Subject {
private Map<String, String> msg = new ConcurrentHashMap<String, String>();
public void pub(String key, String content) {
System.out.println("pub msg: key is " + key + ", content is " + content);
msg.put(key, content);
}
public String sub(String key) {
if (msg.containsKey(key)) {
String ret = msg.get(key);
System.out.println("sub msg: key is " + key + ", result is " + ret);
return ret;
}
return null;
}
}
好,接下来我们来写个动态代理工厂,根据 不同的target来创建动态代理对象
[java]
/**
* SubjectProxyFactory
*
* @author Kevin Fan
* @since 2013-9-13 下午2:47:24
*/
public class SubjectProxyFactory {
//TODO: cache
public static Subject getSubject(final Subject realSubject) {
return (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), new Class[] { Subject.class },
new InvocationHandler() {