手機廠商有代理商,歌星有經紀人,董事長出差由秘書代為結帳——這些都是代理模式。
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 director) { this.director = director; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
director.treat(); // 目標業務
System.out.println("由秘書結帳咯!"); // 代理增強
return null;
}
}
public class ProxyTest {
public static void main(String[] args) {
Director director = new Director();
InvocationHandler secretary = new Secretary(director);
// 生成代理實例
Merchant merchant = (Merchant) Proxy.newProxyInstance(
director.getClass().getClassLoader(),
director.getClass().getInterfaces(),
secretary
);
merchant.treat(); // 調用代理方法
}
}
董事長請大家吃飯 由秘書結帳咯!
$Proxy0),實現目標所有接口