/**
* 委託類,被代理類
*
*/
public class Principal implements Sell {
@Override
public void sell() {
System.out.println("Principal sales");
}
}
/**
* 代理類,靜態代理
*
*/
public class StaticAgent implements Sell {
private Principal principal = new Principal();
@Override
public void sell() {
System.out.println("static");
principal.sell();
}
}
/**
* 動態代理的代理類,不再與委託類實現同一個接口
*
*/
public class DynamicAgent implements InvocationHandler {
private Sell principal = new Principal();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("dynamic");
return method.invoke(principal, args);
}
}
import java.lang.reflect.Proxy;
/**
* 測試類
*/
public class ProxyTest {
public static void main(String[] args) throws Exception{
// 靜態代理
Sell sell1 = new StaticAgent();
sell1.sell();
// 動態代理
DynamicAgent dynamicAgent = new DynamicAgent();
Sell sell2 = (Sell) Proxy.newProxyInstance(Sell.class.getClassLoader(), new Class[]{Sell.class}, dynamicAgent);
sell2.sell();
}
}