1.定义用到的接口
public interface Bussiness {
void doBussiness();
}
public interface Log {
void before();
void after();
}
2.定义接口的实现类
public class BussinessImpl implements Bussiness {
@Override
public void doBussiness() {
System.out.println("业务逻辑部分");
}
}
public class LogImpl implements Log{
@Override
public void before() {
System.out.println("方法执行之前");
}
@Override
public void after() {
System.out.println("方法执行之后");
}
}
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()方法。
@Overridepublic Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
log.before();
Object result = method.invoke(target,args);
log.after();
return result;
}