董事長 (Director) 實作 Merchant 介面,秘書 (Secretary) 代理簽單。
public interface Merchant { void treat(); }
public class Director implements Merchant {
public void treat() { System.out.println("董事長請大家吃飯"); }
}
public class Secretary implements InvocationHandler {
private Director director;
public Secretary(Director d) { director = d; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
director.treat();
System.out.println("由秘書結帳咯!");
return null;
}
}
Merchant proxy = (Merchant) Proxy.newProxyInstance(
Director.class.getClassLoader(),
Director.class.getInterfaces(),
new Secretary(new Director()));
proxy.treat();
董事長請大家吃飯
由秘書結帳咯!
Proxy.newProxyInstance 動態生成實作目標介面的匿名類(如 $Proxy0)。InvocationHandler.invoke(),實現攔截、增強、記錄等橫切關注點。