菜鸟译文(二)——使用Java泛型构造模板方法模式
如果你发现你有很多重复的代码,你可能会考虑用模板方法消除容易出错的重复代码。这里有一个例子:下面的两个类,完成了几乎相同的功能:
- 实例化并初始化一个Reader来读取CSV文件;
- 读取每一行并解析;
- 把每一行的字符填充到Product或Customer对象;
- 将每一个对象添加到Set里;
- 返回Set。
正如你看到的,只有有注释的地方是不一样的。其他所有步骤都是相同的。
ProductCsvReader.java
public class ProductCsvReader {
Set<Product> getAll(File file) throws IOException {
Set<Product> returnSet = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))){
String line = reader.readLine();
while (line != null && !line.trim().equals("")) {
String[] tokens = line.split("\\s*,\\s*");
//不同
Product product = new Product(Integer.parseInt(tokens[0]), tokens[1], new BigDecimal(tokens[2]));
returnSet.add(product);
line = reader.readLine();
}
}
return returnSet;
}
}
CustomerCsvReader.java
public class CustomerCsvReader {
Set<Customer> getAll(File file) throws IOException {
Set<Customer> returnSet = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))){
String line = reader.readLine();
while (line != null && !line.trim().equals("")) {
String[] tokens = line.split("\\s*,\\s*");
//不同
Customer customer = new Customer(Integer.parseInt(tokens[0]), tokens[1], tokens[2], tokens[3]);
returnSet.add(customer);
line = reader.readLine();
}
}
return returnSet;
}
}
对于本例来说,只有两个实体,但是一个真正的系统可能有几十个实体,所以有很多重复易错的代码。你可能会发现Dao层有着相同的情况,在每个Dao进行增删改查的时候几乎都是相同的操作,唯一与不同的是实体和表。让我们重构这些烦人的代码吧。根据GoF设计模式第一部分提到的原则之一,我们应该“封装不同的概念“ProductCsvReader和CustomerCsvReader之间,不同的是有注释的代码。所以我们要做的是,把相同的放到一个类,不同的抽取到另一个类。我们先开始编写ProductCsvReader,我们使用Extract Method提取带注释的部分:
ProductCsvReader.java after Extract Method
public class ProductCsvReader {
Set<Product> getAll(File file) throws IOException {
Set<Product> returnSet = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))){
String line = reader.readLine();
while (line != null && !line.trim().equals("")) {
String[] tokens = line.split("\\s*,\\s*");
Product product = unmarshall(tokens);
returnSet.add(product);
line = reader.readLine();
}
}
return returnSet;
}
Product unmarshall(String[] tokens) {
Product product = new Product(Integer.parseInt(tokens[0]), tokens[1],
new BigDecimal(tokens[2]));
return product;
}
}
现在我们已经把相同(重复)的代码和不同(各自特有)的代码分开了,我们要创建一个父类AbstractCsvReader,它包括两个类(ProductReader和CustomerReader)相同的部分。我们把它定义为一个抽象类,因为我们不需要实例化它。然后我们将使用Pull Up Method重构这个父类。
AbstractCsvReader.java
abstract class AbstractCsvReader {
Set<Product> getAll(File file) throws IOException {
Set<Product> returnSet = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))){
String line = reader.readLine();
while (line != null && !line.trim().equals("")) {
String[] tokens = line.split("\\s*,\\s*");
Product product = unmarshall(tokens);
returnSet.add(product);
line = reader.readLine();
}
}
return returnSet;
}
}
ProductCsvReader.java after Pull Up Method
public class ProductCsvReader extends AbstractCsvReader {
Product unmarshall(String[] tokens) {
Product product = new Product(Integer.parseInt(tokens[0]), tokens[1],
new BigDecimal(tokens[2]));
return product;
}
}
如果在子类中没有‘unmarshall’方法,该类就无法进行编译(它调用unmarshall方法),所以我们要创建一个叫unmarshall的抽象方法。
AbstractCsvReader.java with abstract unmarshall method
abstract class AbstractCsvReader {
Set<Product> getAll(File file) throws IOException {
Set<Product> returnSet = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))){
String line = reader.readLine();
while (line != null && !line.trim().equals("")) {
String[] tokens = line.split("\\s*,\\s*");
Product product = unmarshall(tokens);
returnSet.add(product);
line = reader.readLine();
}
}
return returnSet;
}
abstract Product unmarshall(String[] tokens);
}
现在,在这一点上,AbstractCsvReader是ProductCsvReader的父类,但不是CustomerCsvReader的父类。如果CustomerCsvReader继承AbstractCsvReader编译会报错。为了解决这个问题我们使用泛型。
AbstractCsvReader.java with Generics
abstract class AbstractCsvReader<T> {
Set<T> getAll(File file) throws IOException {
Set<T> returnSet = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))){
String line = reader.readLine();
while (line != null && !line.trim().equals("")) {
String[] tokens = line.split("\\s*,\\s*");
T element = unmarshall(tokens);
returnSet.add(product);
line = reader.readLine();
}
}
return returnSet;
}
abstract T unmarshall(String[] tokens);
}
ProductCsvReader.java with Generics
public class ProductCsvReader extends AbstractCsvReader<Product> {
@Override
Product unmarshall(String[] tokens) {
Product product = new Product(Integer.parseInt(tokens[0]), tokens[1],
new BigDecimal(tokens[2]));
return product;
}
}
CustomerCsvReader.java with Generics
public class CustomerCsvReader extends AbstractCsvReader<Customer> {
@Override
Customer unmarshall(String[] tokens) {
Customer customer = new Customer(Integer.parseInt(tokens[0]), tokens[1],
tokens[2], tokens[3]);
return customer;
}
}
这就是我们要的!不再有重复的代码!父类中的方法是“模板”,它包含这不变的代码。那些变化的东西作为抽象方法,在子类中实现。记住,当你重构的时候,你应该有自动化的单元测试来保证你不会破坏你的代码。我使用JUnit,你可以使用我帖在这里的代码,也可以在这个Github库找一些其他设计模式的例子。在结束之前,我想说一下模板方法的缺点。模板方法依赖于继承,患有 the Fragile Base Class Problem。简单的说就是,修改父类会对继承它的子类造成意想不到的不良影响。事实上,基础设计原则之一的GoF设计模式提倡“多用组合少用继承”,并且许多其他设计模式也告诉你如何避免代码重复,同时又让复杂或容易出错的代码尽量少的依赖继承。欢迎交流,以便我可以提高我的博客质量。
原文地址;Template Method Pattern Example Using Java Generics
翻译的不好,欢迎拍砖!
菜鸟译文(二)——使用Java泛型构造模板方法模式的更多相关文章
- 折腾Java设计模式之模板方法模式
博客原文地址:折腾Java设计模式之模板方法模式 模板方法模式 Define the skeleton of an algorithm in an operation, deferring some ...
- Java基础系列二:Java泛型
该系列博文会告诉你如何从入门到进阶,一步步地学习Java基础知识,并上手进行实战,接着了解每个Java知识点背后的实现原理,更完整地了解整个Java技术体系,形成自己的知识框架. 一.泛型概述 1.定 ...
- Java设计模式之模板方法模式(Template Method)
一.含义 定义一个算法中的操作框架,而将一些步骤延迟到子类中.使得子类可以不改变算法的结构即可重定义该算法的某些特定步骤,不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现. 二 ...
- Java抽象类应用—模板方法模式
模板方法模式(Templete method) 定义一个操作中的算法的骨架,而将一些可变部分的实现延迟到子类中,模板方法模式使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定的步骤. 例: ...
- Java设计模式应用——模板方法模式
所谓模板方法模式,就是在一组方法结构一致,只有部分逻辑不一样时,使用抽象类制作一个逻辑模板,具体是实现类仅仅实现特殊逻辑就行了.类似科举制度八股文,文章结构相同,仅仅具体语句有差异,我们只需要按照八股 ...
- Java设计模式之模板方法模式(Template)
前言: 我们在开发中有很多固定的流程,这些流程有很多步凑是固定的,比如JDBC中获取连接,关闭连接这些流程是固定不变的,变动的只有设置参数,解析结果集这些是根据不同的实体对象“来做调整”,针对这种拥有 ...
- Java/C++实现模板方法模式---数据库操作
对数据库的操作一般包括连接.打开.使用.关闭等步骤,在数据库操作模板类中我们定义了connDB().openDB().useDB().closeDB()四个方法分别对应这四个步骤.对于不同类型的数据库 ...
- java设计模式之模板方法模式
模板方法模式 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中. 模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤.通俗的说的就是有很多相同的步骤的,在某一些地方可能有一些差 ...
- 从西天取经的九九八十一难来看Java设计模式:模板方法模式
目录 示例 模板方法模式 定义 意图 主要解决问题 适用场景 优缺点 西天取经的九九八十一难 示例 当我们设计一个类时,我们能明确它对外提供的某个方法的内部执行步骤, 但一些步骤,不同的子类有不同的行 ...
随机推荐
- spring boot mybatis没有扫描jar中的Mapper接口
只需要在spring boot启动类上加上注解,并指定jar包中接口文件包路径即可 如下: @ComponentScan(basePackages = "com.xx") @Map ...
- LoadRunner监控mysql利器-SiteScope(转)
转自:http://www.jianshu.com/p/fce30e333578 导语 sitescope是惠普出的一个简单易用的监控工具,可以用来监控数据库,系统资源等 一.下载传送门 SiteSc ...
- 基于源码编译安装openssh
最近的,openssl/openssh等相继漏洞的暴露,让暴露在公网的linux.沦陷为肉鸡的正营... 没办法,还是升级版本... 00.openssh简介 OpenSSH 是一组安全远程的连接工 ...
- Linux-静态库生成
Linux上的静态库,其实是目标文件的归档文件.在Linux上创建静态库的步骤如下: 写源文件,通过 gcc -c xxx.c 生成目标文件. 用 ar 归档目标文件,生成静态库. 配合静态库,写一个 ...
- iOS刻度尺换算之1mm等于多少像素理解
刚好看到一个刻度尺文章,实现手机屏幕上画刻度尺. 然后就有一个疑问:这个现实中的1mm(1毫米)长度与手机像素之间的换算比怎么来的呢? 看了下demo代码,发现这样写的: CGFloat sc_w = ...
- 由m种数字组成的n位数有多少个
知乎链接 问题描述 我和我女朋友的QQ号都是九位数字,这九个数字是有七个不同的数字组成的,我想问这种概率是多大,我们是不是特别我看缘分呢?求大神给算一下概率! 思路 定义问题:由7种数字组成的9位数一 ...
- Eclipse导入项目时出错提示 project is missing required library
Eclipse导入(import)项目时出错提示 project is missing required library... 以至于不能build... 然后项目会有红色感叹号: [解决办法] 右击 ...
- 上海租房找房建议及条件,上海IT行业开发常见公司的位置地点
上海租房,找房条件 以2号地铁线为中心,优先选择(回家方便,重点!),交通设施较集中地铁:2,3,4 区:普陀区,静安区,长宁区,闸北区,浦东新区,闵行区,徐汇区 路:镇坪路,威宁路,娄山关路,中山公 ...
- 安卓PopupWindow+ListView实现登录账号选择下拉框
这段时间在做android开发,发现自定义下拉框有很多种方法实现,我介绍一种PopupWindow+ListView的方式,实现起来比较灵活.效果: 直接看核心代码: //获取文本框 etLoginN ...
- 【Android】Android如何实现手机震动
实现手机震动其实很简单,手机震动使用是Vibrator类,然后震动也是需要权限的,在使用之前在AndroidManifest.xml文件中添加 <uses-permission android: ...