常见的设计模式
- spring下默认的bean均为singleton,可以通过singleton=“true|false” 或者 scope=“?”来指定
- spring中的BeanFactory就是简单工厂模式的体现,根据传入一个唯一的标识来获得bean对象,但是否是在传入参数后创建还是传入参数前创建这个要根据具体情况来定。
- java.util.logging.Logger#log() 责任链模式,避免请求的发送者和接收者之间的耦合关系
- java.util.Pattern 解释器模式
- java.util.Iterator、java.util.Scanner 迭代器模式
- java.lang.reflect.Method#invoke() java.util.concurrent.Executor#execute() 中介者模式,集中相关对象之间复杂的沟通和控制方式
- spring ApplicationListener 观察者模式
- spring中在实例化对象的时候用到策略模式
- spring JdbcTemplate中的execute方法、xxxApplicationContext 的refush()方法使用模板方法
- Arrays.asList() 体现的是适配器模式,只是转换接口,后台的数据仍是数组。
- sessionFactory根据客户的每次请求,将dataSource属性设置成不同的数据源,以到达切换数据源的目的。spring中用到的包装器模式在类名上有两种表现:一种是类名中含有Wrapper,另一种是类名中含有Decorator。基本上都是为对象动态添加功能。
- Java 利用缓存来加速大量小对象的访问时间。java.lang.Integer#valueOf(int)
- spring的代理模式在aop中有体现(控制:对功能的限制)
静态代理: 程序运行前就已存在的编译好的代理类。实现步骤:
1、定义业务接口。
2、实现业务接口。
3、定义代理类并实现业务接口,最后通过客户端调用。
动态代理:程序运行期间根据需要动态创建代理类及其实例已完成功能
public class CodingServiceProxy implements CodingService{
private CodingService codingService;
public CodingServiceProxy(CodingService codingService){
this.codingService = codingService;
}
@Override
public String debug(String name) {
System.out.println("预处理...");
String result = codingService.debug(name);
System.out.println(result);
System.out.println("后处理...");
return result;
}
代码重构 - 尽量做到每个方法都可以单元测试
- 大量if/else
- 利用反射处理(效率很低)
private static Map methodsMap = new HashMap<>();
//首先取出状态码,然后根据状态码获得相应的要调用方法的方法名,然后使用java的反射机制就可以实现对应方法的调用了。
static {
// value 是属性CountRecoder的方法名
methodsMap.put(1, "setCountOfFirstStage")