動態代理的應用一例
本例以租房子為例:一.說明:
?? 動態代理可動態為某個類添加代理,以攔截客戶端的調用,在此基礎上進行額外的處理.
?? 目前較流行的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!