java结合项目谈设计模式,浅谈设计模式在JavaWeb项目中的使用

不知道大家是不是跟我有一样的困境,感觉单独拿出一个设计模式,自己能很快的理解,但是要运用到项目中,缺不知道无从下手,于是有了该篇博客,用于记录设计模式在项目中的各种运用场景,不定期能补充:

一定要记得各种设计模式在实际项目中的使用场景

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";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值