引言
对类(class)增强的手段通常分为以下三类
1.继承 子类通过继承父类或者实现接口对类进行增强
2.装饰者模式(Wrapper) 常用于对类的某个方法进行重写,以实现更强大的功能.常用于场合缓冲流,Struct2中StructRequestWarpper类 实现准则:是你还有你,一切全靠你
3.动态代理 一句话概括:获取实现了一组接口的类对象 需提供目标对象,增强建议 三大参数 :ClassLoader Class[] interfaces InvocationHandler (调用目标对象的方法时会调用这)
区别与装饰者模式:装饰者模式通常是对一个类进行加强,而动态代理是获取一组接口的方法在对类进行增强
具体实现
package com.atguigu.spring.aop; 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); }
package com.atguigu.spring.aop; import org.springframework.stereotype.Component; @Component("arithmeticCalculator") public class ArithmeticCalculatorImpl implements ArithmeticCalculator { @Override public int add(int i, int j) { int result = i + j; return result; } @Override public int sub(int i, int j) { int result = i - j; return result; } @Override public int mul(int i, int j) { int result = i * j; return result; } @Override public int div(int i, int j) { int result = i / j; return result; } }
要对Arithmetic 的add,sub,mul,div方法进行增强,添加日志方法,用到了代理
传统的做法
package com.atguigu.spring.aop; public class ArithmeticCalculatorLoggingImpl 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; } }
由以上代码可以看出,相似重复的代码太多,要对改类进行重写成更简单的类,用到了到动态代理
时间: 2024-10-10 02:21:05