Java筆記之對象代理執行個體

來源:互聯網
上載者:User
 代碼如下 複製代碼

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


//代理需要實現的介面
interface IVehical {

    //例如我這裡寫了兩個介面
    void run();
    void say();
}

//concrete implementation
 class Car implements IVehical{

    //下面這兩個方法,作為介面的實現方法,如果介面中沒有這些方法,而在這裡出現了多餘的方法程式將編譯不過。
    //每次調用這兩個方法都會觸發代理對象中的invoke方法。
    public void run() {
    System.out.println("Car is running");
    }
   
    public void say()
    {
        System.out.println("just one!");
    }

}

//proxy class
//這個類是用來建立代理對象的,這裡只是對它進行了簡單的封裝
class VehicalProxy {

    private IVehical vehical;

    public VehicalProxy(IVehical vehical) {
    this.vehical = vehical;
    }
    //這個方法返回建立後的對象代理
    public IVehical create(){
    final Class<?>[] interfaces = new Class[]{IVehical.class};
    final VehicalInvacationHandler handler = new VehicalInvacationHandler(vehical);
   
    return (IVehical) Proxy.newProxyInstance(IVehical.class.getClassLoader(), interfaces, (InvocationHandler) handler);
    }
    //這個是跟代理對象綁定的一個處理器,www.111cn.net每次調用對象代理中的方法都會觸發這個處理器中的invoke方法
    class VehicalInvacationHandler implements InvocationHandler{

    private final IVehical vehical;
   
    public VehicalInvacationHandler(IVehical vehical) {
        this.vehical = vehical;
    }

    //每當執行對象代理的say或者call(只要是IVehical介面中的方法)就會觸發invoke被執行
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {

        System.out.println("--before running...");
        Object ret = method.invoke(vehical, args);
        System.out.println("--after running...");
       
        return ret;
    }
   
    }
}

class Main {
    public static void main(String[] args) {
   
    IVehical car = new Car();
    VehicalProxy proxy = new VehicalProxy(car);
   
    IVehical proxyObj = proxy.create();
    proxyObj.say();
    }
}

/*
 * 程式運行之後將列印如下資訊,因此我們可以看出對象的代理可以往特定對象的方法中添加附帶的執行代碼,
 * 這個的作用在我們需要對一個做日誌或者bug調試的時候非常有作用,因為我們不應該把調試代碼或者是打
 * 印日誌代碼寫在對象中,這樣我們就可以將日誌的代碼添加到對象的代理中,從而將業務與程式的架構相
 * 關的功能分離,從而保證了代碼的“純淨性”。
 * output:
 * --before running...
 * Car is running
 * --after running...
 * */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.