Spring阶段性学习总结(十)AOP编程入门学习之动态代理实现代码的优化

1 public interface Calculator {
2     int add(int i, int j);
3     int sub(int i, int j);
4     int mul(int i, int j);
5     int div(int i, int j);
6 }
 1 public class CalculatorImp  implements  Calculator{
 2         /*
 3         * 如果在每个方法中添加想赢的输出日志,那么维护起来相当困难,而且,
 4         * 代码结构也破坏了,掺杂了多余的非功能性代码,所以这种方式不可取。
 5         * 首先使用动态代理的方式解决这个问题,进而引出AOP切面编程的思路
 6         * */
 7     @Override
 8     public int add(int i, int j) {
 9         int result=i+j;
10         return result;
11     }
12 
13     @Override
14     public int sub(int i, int j) {
15         int result=i-j;
16         return result;
17     }
18 
19     @Override
20     public int mul(int i, int j) {
21         int result=i*j;
22         return result;
23     }
24 
25     @Override
26     public int div(int i, int j) {
27         int result=i/j;
28         return result;
29     }
30 }
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class CalculatorLoggingProxy {
    //定义一个构造函数接收Calculator对象
    public CalculatorLoggingProxy(Calculator calculator){
        this.target=calculator;
    }
    //定义一个要代理的对象
    private Calculator target;

    public Calculator getLoggingProxy() {
        Calculator proxy = null;
        //定义一个类加载器,为代理对象服务
        ClassLoader classLoader = target.getClass().getClassLoader();
        //代理对象的类型,即其中有哪些方法
        Class[] interfaces = new Class[]{Calculator.class};
        //当调用代理对象所拥有的方法时,以下代码会被执行
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                System.out.println("Method:"+method.getName()+" BeginWith:"+ Arrays.asList(args));
                Object result = method.invoke(target, args);
                //Object result = h.invoke(target, args);
                System.out.println("The Method end with :"+result.toString());
                return result;
            }

        };
        proxy = (Calculator) Proxy.newProxyInstance(classLoader, interfaces, h);
        return proxy;
    }
}
 3 public class Main {
 4     public static void main(String[] args) {
 5         Calculator calculator=new CalculatorImp();
 6         Calculator loggingProxy = new CalculatorLoggingProxy(calculator).getLoggingProxy();
 7         int result=loggingProxy.add(1,2);
 8         result=loggingProxy.div(4,2);
 9 
10     }
11 }