定义一个ArithmeticCalculator接口
public interface ArithmeticCalculator {
int add(int i,int j);
int sub(int i,int j);
int mul(int i,int j);
int div(int i,int j);
}
写出ArithmeticCalculatorImpl类实现接口ArithmeticCalculator,为了跟踪程序,输出语句很烦(日志同理)
public class ArithmeticCalculatorImpl implements ArithmeticCalculator{
@Override
public int add(int i, int j) {
System.out.println("The method add begins with ["+i+","+j+"]");
int result=i+j;
System.out.println("The method add ends with"+result);
return result;
}
@Override
public int sub(int i, int j) {
System.out.println("The method sub begins with ["+i+","+j+"]");
int result =i-j;
System.out.println("The method sub ends with"+result);
return result;
}
@Override
public int mul(int i, int j) {
System.out.println("The method mul begins with ["+i+","+j+"]");
int result=i*j;
System.out.println("The method mul ends with"+result);
return result;
}
@Override
public int div(int i, int j) {
System.out.println("The method div begins with ["+i+","+j+"]");
int result=i/j;
System.out.println("The method div ends with"+result);
return result;
}
}
使用动态代理对象来处理,把输出语句去掉,写一个ArithmeticCalculatorLoggingProxy类
public class ArithmeticCalculatorLoggingProxy {
//要代理的对象
private ArithmeticCalculator target;
public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
super();
this.target = target;
}
public ArithmeticCalculator getLoggingProxy()
{
ArithmeticCalculator proxy=null;
//代理对象由那一个类加载器负责加载
ClassLoader loader=target.getClass().getClassLoader();
//代理对象的类型,即其中有哪些方法
Class[] interfaces=new Class[]{ArithmeticCalculator.class};
//当调用代理对象其中的方法时,该执行的代码
InvocationHandler h=new InvocationHandler(){
/*
* proxy:正在返回的哪个代理对象
* method:正在被调用的方法
* args:调用方法时,传入的参数*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String methodName=method.getName();
//日志
System.out.println("The method"+methodName+"begins with "+Arrays.asList(args));
//执行方法
Object result=method.invoke(target, args);
//日志
System.out.println("The method "+methodName+"begins with "+result);
return result;
}
};
proxy=(ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
}
用主函数测试
```
ArithmeticCalculator target=new ArithmeticCalculatorImpl();
ArithmeticCalculator proxy=new ArithmeticCalculatorLoggingProxy(target).getLoggingProxy();
int result=proxy.add(104, 52);
System.out.println("-->"+result);
result=proxy.div(10, 2);
System.out.println("-->"+result);
```
使用动态代理后,代码复用提高,代码集中,代码量减少(假如实现类很复杂)。