代理模式:为其他对象提供一种代理以控制对这个对象的访问。
静态代理
代码语言:javascript复制public interface House {
void buyHosue();
}
代码语言:javascript复制public class BuyHouse implements House {
@Override
public void buyHosue() {
System.out.println("我要买房");
}
}
代码语言:javascript复制public class BuyHouseProxy implements House {
private House house;
public BuyHouseProxy(final House house) {
this.house = house;
}
@Override
public void buyHosue() {
System.out.println("买房前准备");
house.buyHosue();
System.out.println("买房后装修");
}
}
代码语言:javascript复制public class ProxyTest {
public static void main(String[] args) {
House house = new BuyHouse();
house.buyHosue();
BuyHouseProxy buyHouseProxy = new BuyHouseProxy(house);
buyHouseProxy.buyHosue();
}
}
动态代理
代码语言:javascript复制import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxyHandler implements InvocationHandler {
private Object object;
public DynamicProxyHandler(final Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("买房前准备");
Object result = method.invoke(object, args);
System.out.println("买房后装修");
return result;
}
}
代码语言:javascript复制import java.lang.reflect.Proxy;
public class DynamicProxyTest {
public static void main(String[] args) {
House house = new BuyHouse();
House proxyBuyHouse = (House) Proxy.newProxyInstance(House.class.getClassLoader(), new
Class[]{House.class}, new DynamicProxyHandler(house));
proxyBuyHouse.buyHosue();
}
}
注意Proxy.newProxyInstance()方法接受三个参数:
ClassLoader loader
:指定当前目标对象使用的类加载器,获取加载器的方法是固定的Class<?>[] interfaces
:指定目标对象实现的接口的类型,使用泛型方式确认类型InvocationHandler:
指定动态处理器,
执行目标对象的方法时,会触发事件处理器的方法