转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/8744002
今天你还是像往常一样来上班,一如既往地开始了你的编程工作。
项目经理告诉你,今天想在服务器端增加一个新功能,希望写一个方法,能对Book对象进行处理,将Book对象的所有字段以XML格式进行包装,这样以后可以方便与客户端进行交互。并且在包装开始前和结束后要打印日志,这样方便调试和问题定位。
没问题!你觉得这个功能简直是小菜一碟,非常自信地开始写起代码。
Book对象代码如下:
public class Book {
private String bookName;
private int pages;
private double price;
private String author;
private String isbn;
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
}
然后写一个类专门用于将Book对象包装成XML格式:
public class Formatter {
public String formatBook(Book book) {
System.out.println("format begins");
String result = "";
result += "<book_name>" + book.getBookName() + "</book_name>\n";
result += "<pages>" + book.getPages() + "</pages>\n";
result += "<price>" + book.getPrice() + "</price>\n";
result += "<author>" + book.getAuthor() + "</author>\n";
result += "<isbn>" + book.getIsbn() + "</isbn>\n";
System.out.println("format finished");
return result;
}
}
调用代码如下:
public class Test {
public static void main(String[] args) throws Exception {
Book book = new Book();
book.setBookName("Thinking in Java");
book.setPages(880);
book.setPrice(68);
book.setAuthor("Bruce Eckel");
book.setIsbn("9787111213826");
Formatter formatter = new Formatter();
String result = formatter.formatBook(book);
System.out.println(result);
}
}
你写好了之后,迫不及待地开始运行,运行结果也完全符合你的期望。
项目经理看完后,对你非常满意,小伙效率很高的嘛!你也非常的得意。
不过两天之后,项目经理又找到了你,他说之前没有考虑到需要交互的客户端还包括手机设备,而手机设备都比较吃流量,用XML格式来传输太耗流量了,想最好能改成使用JSON格式传输。但是之前的XML格式也要保留,最好可以由客户端指定使用哪种格式。
你有些不开心,心里低估着,为什么一开始不考虑周全呢,现在又要改遗留代码。但对方毕竟是领导,你还是要服从命令的,于是你开始修改Formatter类:
public class Formatter {
public static final int XML = 0;
public static final int JSON = 1;
public String formatBook(Book book, int format) {
System.out.println("format begins");
String result = "";
if (format == XML) {
result += "<book_name>" + book.getBookName() + "</book_name>\n";
result += "<pages>" + book.getPages() + "</pages>\n";
result += "<price>" + book.getPrice() + "</price>\n";
result += "<author>" + book.getAuthor() + "</author>\n";
result += "<isbn>" + book.getIsbn() + "</isbn>\n";
} else if (format == JSON) {
result += "{\n";
result += "\"book_name\" : \"" + book.getBookName() + "\",\n";
result += "\"pages\" : \"" + book.getPages() + "\",\n";
result += "\"price\" : \"" + book.getPrice() + "\",\n";
result += "\"author\" : \"" + book.getAuthor() + "\",\n";
result += "\"isbn\" : \"" + book.getIsbn() + "\",\n";
result += "}";
}
System.out.println("format finished");
return result;
}
}
调用代码如下:
public class Test {
public static void main(String[] args) throws Exception {
Book book = new Book();
book.setBookName("Thinking in Java");
book.setPages(880);
book.setPrice(68);
book.setAuthor("Bruce Eckel");
book.setIsbn("9787111213826");
Formatter formatter = new Formatter();
String result = formatter.formatBook(book, Formatter.XML);
System.out.println(result);
result = formatter.formatBook(book, Formatter.JSON);
System.out.println(result);
}
}
再次运行程序,得到了以下结果。
项目经理看到运行结果后开心地说:“太好了,这正是我想要的!”
可是你这次却没有那么开心,你觉得代码已经有些混乱了,XML格式的逻辑和JSON格式的逻辑混淆在一起,非常不利于阅读,而且如果以后还需要扩展功能也会非常困难。好在传输格式一般也就XML和JSON了,应该不会再有什么扩展了,你这样安慰自己道。
但幻想总会被现实打破,“我最近听说有个YAML格式挺好玩的.......” 项目经理说道。这个时候你已经有想打人的冲动了!!!
很多时候就是这样,在公司里写的代码乱七八糟,质量极差,很大一部分原因就是因为需求变来变去。我们不断在原有代码基础上补充各种后续加入的情况,在一行行新增的if语句下面,我们的代码变得不堪入目。当然,我们作为程序员,对于需求这种东西没有太多的话语权,在这方面我们无能为力。但是我们可以尽量地把程序的架构设计好,让我们写出的代码更具有扩展性,这样就可以应对各种需求变更了。
下面你将要使用23种设计模式中的模板方法来改进以上程序。
首先将Formatter中的代码进行修改,如下所示:
public abstract class Formatter {
public String formatBook(Book book, int format) {
beforeFormat();
String result = formating(book);
afterFormat();
return result;
}
protected void beforeFormat() {
System.out.println("format begins");
}
protected abstract String formating(Book book);
protected void afterFormat() {
System.out.println("format finished");
}
}
你会发现format_book方法只有四步,第一步调用before_format,去打印格式转换前的日志。第二步调用formating,这个方法是个抽象方法,用于处理具体的转换逻辑,因此每一个继承自Formatter的子类都需要重写此方法,来实现各自的转换逻辑。第三步调用after_format,去打印格式转换后的日志。第四步返回result。由于类中存在了抽象方法,我们也就需要把Formatter声明成抽象类。
然后要定义专门的子类来处理每种传输格式的具体逻辑,这样不同传输格式的逻辑可以从一个方法里分离开,明显便于阅读和理解。
定义类XMLFormatter继承自Formatter,里面加入处理XML格式的具体逻辑:
public class XMLFormatter extends Formatter {
@Override
protected String formating(Book book) {
String result = "";
result += "<book_name>" + book.getBookName() + "</book_name>\n";
result += "<pages>" + book.getPages() + "</pages>\n";
result += "<price>" + book.getPrice() + "</price>\n";
result += "<author>" + book.getAuthor() + "</author>\n";
result += "<isbn>" + book.getIsbn() + "</isbn>\n";
return result;
}
}
定义类JSONFormatter继承自Formatter,里面加入处理JSON格式的具体逻辑:
public class JSONFormatter extends Formatter {
@Override
protected String formating(Book book) {
String result = "";
result += "{\n";
result += "\"book_name\" : \"" + book.getBookName() + "\",\n";
result += "\"pages\" : \"" + book.getPages() + "\",\n";
result += "\"price\" : \"" + book.getPrice() + "\",\n";
result += "\"author\" : \"" + book.getAuthor() + "\",\n";
result += "\"isbn\" : \"" + book.getIsbn() + "\",\n";
result += "}";
return result;
}
}
最后调用代码如下:
public class Test {
public static void main(String[] args) throws Exception {
Book book = new Book();
book.setBookName("Thinking in Java");
book.setPages(880);
book.setPrice(68);
book.setAuthor("Bruce Eckel");
book.setIsbn("9787111213826");
XMLFormatter xmlFormatter = new XMLFormatter();
String result = xmlFormatter.formatBook(book);
System.out.println(result);
JSONFormatter jsonFormatter = new JSONFormatter();
result = jsonFormatter.formatBook(book);
System.out.println(result);
}
}
运行之后,你会发现运行结果和修改前代码的运行结果完全相同。但是使用模板方法之后,代码的可读性有了很大的提高,因为处理格式转换的代码都放到了各自的类当中,而不是全部塞进一个方法中。并且在扩展性上也有了很大的提升,比如你开始感兴趣项目经理说的YAML格式了。
定义类YAMLFormatter继承自Formatter,里面加入处理YAML格式的具体逻辑:
public class YAMLFormatter extends Formatter {
@Override
protected String formating(Book book) {
String result = "";
result += "book_name: " + book.getBookName() + "\n";
result += "pages: " + book.getPages() + "\n";
result += "price: " + book.getPrice() + "\n";
result += "author: " + book.getAuthor() + "\n";
result += "isbn: " + book.getIsbn() + "\n";
return result;
}
}
调用代码只需要加入:
YAMLFormatter yamlFormatter = new YAMLFormatter();
String result = yamlFormatter.formatBook(book);
System.out.println(result);
好了,令人头疼的YAML格式就这样被支持了,只需要在调用的时候决定是实例化XMLFormatter,JSONFormatter还是YAMLFormatter,就可以按照相应的规格进行格式转换了。而且整体的代码很有条理,看起来也很舒心。这个时候,你会轻松地向项目经理调侃一句,还有需要支持的格式吗?
模板方法: 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
分享到:
相关推荐
(新高考适用)4 任务群四 古典诗歌鉴赏4 微视角 高考诗歌鉴赏典型题型归类透析 课件——2021届高考语文冲刺复习.ppt
Java深入解析 透析Java本质的36个话题
银行互联网贷款发展透析——以青岛地区为例.pdf
《Java深入解析 透析Java本质的36个话题》这本书是Java开发者的重要参考资料,它涵盖了Java编程中的关键概念和技术,旨在帮助读者深入理解Java语言的本质。以下将根据标题和描述,结合Java这一主题,详细阐述书中...
自己花钱买的高清、完整版、带...本书分为5 章,分别为“基本概念”,“运算符与表达式”,“String类”,“方法、构造器与变量”,“类与接口”。通过以上方面介绍那些常见、常用却少为人知的Java 知识。值得你一阅。
本文将深入探讨分布式环境下Session丢失的问题及其解决方法,并通过阿里P7级技术专家的实际案例分享和源码分析来提供全面的技术指导。 #### 二、分布式环境下Session丢失的原因 1. **会话状态集中存储:** 在...
深入讲解WINDOWS网络编程中的“乾坤大挪移”——原始套接字的原理及用法。内中更有示例代码,教你实现ARP欺骗,洪水攻击,服务拒绝攻击等网络安全软件,还有相应的防范手段。绝对的好书,隆重推荐!
一次学习终身受用-如何正确使用设计模式写出优雅的代码 年薪60万大咖深入浅出带你玩转大型互联网企业DevOps利器-Docker 架构知识透析:深入了解高并发通信模型NIO 除了上面还有Java面试集棉电子书,对于初学者和面试...
高校教材管理新模式透析.doc
首先,设计模式是经过验证的、在特定情境下解决常见问题的解决方案模板。它们不是具体的代码实现,而是描述了在特定情况下如何组织和交互对象的一种通用方法。设计模式通常分为创建型、结构型和行为型三大类,如工厂...
应用架构之魂设计模式实战演练应用架构之魂设计模式实战演练 揭开springAOP神秘面纱(动态代理) Mysql性能优化之索引优化 写实现Tomcat服务器 移动后台端框架设计 公司级框架原理解析 解密公司内部框架开发(打造属于...
基于“四性医疗”理念的血液透析机管理方法探讨 摘要:本文基于“四性医疗”理念,探讨血液透析机的管理方法,以提高设备管理水平,降低设备故障率及使用风险,保障患者治疗安全。 一、血液透析机的管理现状 血液...
血液透析风险的防控方法.doc
《创造信息时代的大学科研文化——杜德斯达特科研方式变革观透析》这篇文章深入探讨了在信息时代背景下,大学科研文化的转变及其重要性。文章指出,科研水平和实力不仅是衡量大学教学质量和社会服务的关键因素,也是...
建立了通过透析和喷雾干燥从猪肠粘膜中提取粗肝素钠的方法。 猪肠粘膜按以下步骤处理:酶解,树脂交换吸附-洗涤,洗脱,压力过滤,透析,喷雾干燥。 使用肝素抗IIa因子测定试剂盒测量产物的活性。 用这种方法制得的...
透析模式学习主要探讨了不同类型的血液透析技术及其特点,包括低通量血液透析、高通量血液透析、血液滤过、血液透析滤过和血液灌流,以及一个简短提及的单纯超滤。以下是这些透析模式的详细解释: 1. 低通量血液...
水生态文明城市建设的支持保障技术——超磁透析原位生态修复钟晓红联盟技术推介PPT学习教案.pptx
目前主要采用两种透析方法:腹膜透析与血液透析。其中,血液透析需要借助专门的透析机来完成过滤过程,而本文主要探讨的是血液透析中的温度控制问题。 #### 血液透析原理概述 在血液透析过程中,血液首先通过特殊...