代理模式分静态代理和动态代理,动态代理是依靠反射机制来实现的。在不适合直接对一个原对象操作的时候,就可以用到代理模式,靠一个代理对象来执行对这个原对象的操作。
示例如下:
public class Proxy {
public static void main(String[] args){
Proxy proxy=new Proxy();
BuyWater buyWater = proxy.new BuyWater();
BuyProxy buyProxy=proxy.new BuyProxy(buyWater);
IBuyFood iBuyFood = (IBuyFood) java.lang.reflect.Proxy.newProxyInstance(buyProxy.getClass().getClassLoader(),buyWater.getClass().getInterfaces(),buyProxy);
iBuyFood.buy(300);
}
interface IBuyFood{
void buy(int money);
}
class BuyWater implements IBuyFood{
@Override
public void buy(int money) {
System.out.println("买水花了"+money+"元");
}
}
class BuyProxy implements InvocationHandler{
private Object object;
public BuyProxy(Object object) {
this.object = object;
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
Object result = method.invoke(object,objects);
return result;
}
}
}
网友评论