1.定義用到的接口 java
public interface Bussiness {
void doBussiness();
} ide
public interface Log {
void before();
void after();
} this
2.定義接口的實現類 代理
public class BussinessImpl implements Bussiness { 接口
@Override
public void doBussiness() {
System.out.println("業務邏輯部分");
}
} get
public class LogImpl implements Log{ io
@Override
public void before() {
System.out.println("方法執行以前");
} class
@Override
public void after() {
System.out.println("方法執行以後");
} import
} 方法
3.這是實現代理最關鍵的類Handler 須要實現InvocationHandler 重寫invoke()方法
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Handler implements InvocationHandler {
private Bussiness target = null;
private Log log = null;
public void setTarget(Bussiness target){
this.target = target;
}
public void setLog(Log log){
this.log = log;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
log.before();
Object result = method.invoke(target,args);
log.after();
return result;
}
public Object getProxy(){
Bussiness buss = (Bussiness)Proxy.newProxyInstance(target.getClass().getClassLoader() ,
target.getClass().getInterfaces(),this);
return buss;
}
}
4.工廠類的簡單實現
public class Factory {
/**
* @param args
*/
public static void main(String[] args) {
BussinessImpl impl = new BussinessImpl();
LogImpl logImpl = new LogImpl();
Handler handler = new Handler();
handler.setLog(logImpl);
handler.setTarget(impl);
Bussiness buss = (Bussiness) handler.getProxy();
buss.doBussiness();
}
}
Bussiness buss = (Bussiness) handler.getProxy();
buss.doBussiness();
當調用代理類的方法時 會調用Handler的invoke()方法。
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log.before(); Object result = method.invoke(target,args); log.after(); return result; }