代理模式学习
采用动态代理
以房东租房为例
- 首先得定义一个接口
public interface Rent {
public void rent();
public void sell();
public void rise();
}
- 定义一个房东类实现具体得接口
public class Landlord implements Rent{
@Override
public void rent(){
System.out.println("房东出租房子");
}
@Override
public void sell() {
System.out.println("房东要卖房子");
}
@Override
public void rise() {
System.out.println("房东要涨租");
}
}
接下来是重点,如何通过InvocationHandler这个接口去实现一个代理,这个模板比较通用,可以作为任意对象得代理,只不过我这里
public class ProxyInvocation implements InvocationHandler
- 声明一个对象
private Object object;
2.使用Set方法给对象赋予实体(当然也可以通过构造函数赋予)
public void setObject(Object object) {
this.object = object;
}
3.获取代理 使用Proxy得newProxyInstance静态方法获取一个代理对象(此对象相当于中介)
//newProxyInstance参数说明
//1– the class loader to define the proxy class
//2 – the list of interfaces for the proxy class to implement
//3 – the invocation handler to dispatch method invocations to
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), this.object.getClass().getInterfaces(),this);
}
4.重写invoke函数 实际上就是代理具体方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("执行了"+method.getName()+"方法");
Object result = method.invoke(object, args);
return result;
}
最后用户通过代理来实现landlord得方法,并且附加一些代理自由得方法。
public class Test {
public static void main(String[] args) {
Landlord landlord = new Landlord();
ProxyInvocation proxyInvocation = new ProxyInvocation();
proxyInvocation.setObject(landlord);
Rent proxy = (Rent)proxyInvocation.getProxy();
proxy.rent();
proxy.sell();
proxy.rise();
}
}