本例以租房子为例:
一.说明:
动态代理可动态为某个类添加代理,以拦截客户端的调用,在此基础上进行额外的处理.
目前较流行的AOP技术,就有以动态代理为技术基础进行实现的.
本例中,中介作为房子的动态代理,所有调用房子的方法,必须经过中介类(HouseAgency).
二.源代码:
1.House接口:
public interface House {
public void rent();
public int getPrice();
}
2.House接口实现类ConcreateHouse:
public class ConcreteHouse implements House{
private int price;
public ConcreteHouse(int price){
this.price=price;
}
public void rent(){
System.out.println("rent ok!");
}
public int getPrice(){
return price;
}
}
3.实现InvocationHandler接口的中介类:
import java.lang.reflect.*;
public class HouseAgency implements InvocationHandler {
private Object house;
public HouseAgency(Object house){
this.house=house;
}
public HouseAgency(){}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result=null;
if("getPrice".equals(method.getName())){
System.out.println("invoking getPrice() to query rent price.");
}
if("rent".equals(method.getName())){
System.out.println("invoking rent() to rent the house.");
}
result=method.invoke(house,args);
return result;
}
}
4.客户端
import java.lang.reflect.*;
public class HouseClient{
public static void main(String[] args){
ConcreteHouse house1=new ConcreteHouse(400);
HouseAgency ha=new HouseAgency(house1);
House house=(House)Proxy.newProxyInstance(house1.getClass().getClassLoader(),
house1.getClass().getInterfaces(),ha);
int price=house.getPrice();
System.out.println("the house rent is : "+price);
if(price>300){
house.rent();
}
}
}
三:打印结果
invoking getPrice() to query rent price.
the house rent is : 400
invoking rent() to rent the house.
rent ok!