不知道大家是不是跟我有一样的困境,感觉单独拿出一个设计模式,自己能很快的理解,但是要运用到项目中,缺不知道无从下手,于是有了该篇博客,用于记录设计模式在项目中的各种运用场景,不定期能补充:
一定要记得各种设计模式在实际项目中的使用场景
1. 单例模式
package singleton;
public class SingleTon4 {
private static class SingleTonHolder{
private static final SingleTon4 instance = new SingleTon4();
}
private SingleTon4(){
}
//这种方式同样利用了classloder的机制来保证初始化instance时只有一个线程,并且可以懒加载
public static final SingleTon4 getInstance(){
return SingleTonHolder.instance;
}
}
项目使用情景:
spring管理bean默认就是单例模式 prototype=singleton ,可以通过配置修改为多例等其他模式
2. 模板模式
模板模式就是通过抽象类来定义一个逻辑模板,逻辑框架、逻辑原型,然后将无法决定的部分抽象成抽象类交由子类来实现,一般这些抽象类的调用逻辑还是在抽象类中完成的
如下实例,定义一个抽象的Controller,
统一路径跳转格式
其他公共的方法
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
public abstract class SpringBasicController {
public SpringBasicController() {
}
//时间格式初始化
@InitBinder
protected void initBinder(WebDataBinder binder, HttpServletRequest request, HttpServletResponse response) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Timestamp.class, new TimestampEditor(dateFormat, true));
binder.registerCustomEditor(Date.class, new DateEditor());
binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, true));
}
public abstract String getFModulePath();
public abstract String getModulePath();
public String getPath(String name) {
return this.getFModulePath() + "/" + this.getModulePath() + "/" + name;
}
public String getPathList() {
return this.getFModulePath() + "/" + this.getModulePath() + "/list";
}
public String getPathAdd() {
return this.getFModulePath() + "/" + this.getModulePath() + "/add";
}
public String getPathUpdate() {
return this.getFModulePath() + "/" + this.getModulePath() + "/update";
}
}