Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 代理模式:靜態代理與動態代理完全解析

什麼是代理模式

在某些情境下,客戶端並不想、也無法直接引用某個物件,這時就可以透過一個稱為「代理」的第三者來完成間接引用。代理物件充當客戶端與目標物件之間的中介,既能過濾掉客戶端不該看到的內容與服務,也能為其附加額外的功能。

簡單來說,代理模式就是透過一個代理物件去存取真正的目標物件,並且能像裝飾模式那樣,為物件加上一些額外的行為。

靜態代理

靜態代理指的是:代理類別在程式執行「之前」就已經寫好,也就是我們在撰寫程式碼時便預先定義了代理類。相對地,動態代理則是在程式執行「期間」才自動產生代理類。

先看一段程式碼會更直觀:

Main:

public class Main {
    public static void main(String[] args) {
        Water water = new Water();
        WaterProxy waterProxy = new WaterProxy(water);
        waterProxy.drink();
    }
}

介面:

// 代理類與被代理類共同實作的介面
public interface Drink {
    void drink();
}

被代理類:

public class Water implements Drink {
    @Override
    public void drink() {
        System.out.println("drink water");
    }
}

代理類:

// 與被代理類實作同一個介面
public class DrinkProxy implements Drink {
    private Drink drinkImpl;
    // 透過建構子傳入 Water 物件
    public DrinkProxy(Drink drinkImpl) {
        this.drinkImpl = drinkImpl;
    }
    @Override
    public void drink() {
        System.out.println("before drink");
        drinkImpl.drink();
        System.out.println("after drink");
    }
}

執行結果:

before drink
drink water
after drink

動態代理

有時候我們只是換一個被代理的類,而代理物件在呼叫真實方法前後所做的事卻一模一樣——所謂「鐵打的代理類,流水的被代理類」。若採用靜態代理,就只能代理實作了同一介面的類,想代理任意類就得寫出一大堆重複的代理類。這時動態代理派上用場,而 Java 早已提供了一套便利的工具。

java.lang.reflect.Proxy 類別中可動態產生代理物件的方法:

/**
 * 回傳實作了指定介面的物件,呼叫代理物件的方法會轉而呼叫
 * InvocationHandler 的 invoke 方法
 *
 * @param loader     產生代理類所使用的類別載入器
 * @param interfaces 代理類所要實作的介面
 * @param h          實作了 InvocationHandler 介面的物件
 * @return 代理物件
 */
public static Object newProxyInstance(ClassLoader loader,
        Class<?>[] interfaces, InvocationHandler h)

InvocationHandler 介面:

/**
 * 每個代理類都有一個關聯的 InvocationHandler,
 * 當代理物件執行某方法時,會直接執行 invoke 方法
 */
public interface InvocationHandler {
    /**
     * @param proxy 呼叫該方法的代理物件
     * @param method 代理物件所呼叫的方法
     * @param args 呼叫方法的參數
     * @return 呼叫方法的回傳值
     */
    public Object invoke(Object proxy, Method method, Object[] args)
}

實際範例——InvocationHandler 的實作類:

public class CommonInvocationHandler implements InvocationHandler {
    private Object proxied;
    public CommonInvocationHandler(Object proxied) {
        this.proxied = proxied;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before doing something");
        Object result = method.invoke(proxied, args);
        System.out.println("after doing something");
        return result;
    }
}

Main:

public class Main {
    public static void main(String[] args) {
        Water water = new Water();
        Drink waterProxy = (Drink) Proxy.newProxyInstance(
            water.getClass().getClassLoader(),
            water.getClass().getInterfaces(),
            new CommonInvocationHandler(water));
        waterProxy.drink();
    }
}

輸出結果:

before doing something
drink water
after doing something

此外,也可以不需要具體的被代理物件,但必須有對應的介面(沒有實作介面的類可改用 cglib 實作動態代理)。近來相當熱門的 Retrofit,正是直接透過宣告好的介面,利用動態代理完成網路請求。

模仿 Retrofit 的簡化範例

POST 註解:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface POST {
    String value() default "";
}

Query 註解:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Query {
    String value() default "";
}

Service 介面:

public interface Service {
    // 用 POST 註解宣告請求方式與相對路徑
    @POST("/login")
    // 用 Query 註解宣告請求的參數名
    void login(@Query("username") String username,
               @Query("password") String password);
}

Main:

public class Main {
    public static void main(String[] args) {
        // 動態取得 Service 介面的代理
        Service service = (Service) Proxy.newProxyInstance(
            Service.class.getClassLoader(),
            new Class[] { Service.class },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 透過註解取得請求的相對路徑
                    String relativePath = ((POST) method.getAnnotations()[0]).value();
                    System.out.println("relative path: " + relativePath);
                    // 取得參數的註解
                    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
                    // 透過參數註解取得請求參數
                    for (int i = 0; i < parameterAnnotations.length; i++) {
                        if (parameterAnnotations[i].length != 0) {
                            for (int j = 0; j < parameterAnnotations[i].length; j++) {
                                Query query = (Query) parameterAnnotations[i][j];
                                System.out.println(query.value() + ": " + args[i].toString());
                            }
                        }
                    }
                    return null;
                }
            });
        service.login("hello", "world");
    }
}
Copyright © Linux教程網 All Rights Reserved