Java动态代理模式

动态代理是为了弥补静态代理的不足,概念等同于普通的代理模式,在实现上稍有区别。

涉及一个接口一个类:

InvocationHandler
Proxy

角色代码准备:

抽象角色:

public interface IBook {
	String getBookName();

	String getBookPress();
}

真实角色:

public class JavaBook implements IBook {

	@Override
	public String getBookName() {
		return "Java 程序设计";
	}

	@Override
	public String getBookPress() {
		return "上海科学出版社";
	}

}

其他行为:

public class Something {
	public void start() {
		System.out.println("获取图书价格成功");
	}

	public void end() {
		System.out.println("后续可以阅读");
	}
}

代理角色:

public class DynamicProxyBook implements InvocationHandler {
	private Object target;
	private Object others;

	public Object bind(Object target, Object others) {
		this.others = others;
		this.target = target;
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass()
		        .getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Class clazz = this.others.getClass();
		Method start = clazz.getDeclaredMethod("start");
		
		start.invoke(this.others);
		Object result = method.invoke(target);
		System.out.println("result:"+result);
		Method end = clazz.getDeclaredMethod("end");
		start.invoke(this.others);
		return result;
	}

}

测试代码:

public static void main(String[] args) {
	IBook book = (IBook) new DynamicProxyBook().bind(new JavaBook(), new Something());
	book.getBookName();
	book.getBookPress();
}

 

不足:

1.接口必须有具体的显示实现类而不能动态绑定

 

你可能感兴趣的:(java动态代理)