Java设计模式透析之 —— 模板方法(Template Method)

转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/8744002

今天你还是像往常一样来上班,一如既往地开始了你的编程工作。

项目经理告诉你,今天想在服务器端增加一个新功能,希望写一个方法,能对Book对象进行处理,将Book对象的所有字段以XML格式进行包装,这样以后可以方便与客户端进行交互。并且在包装开始前和结束后要打印日志,这样方便调试和问题定位。

没问题!你觉得这个功能简直是小菜一碟,非常自信地开始写起代码。

Book对象代码如下:

[java]  view plain copy
  1. public class Book {  
  2.   
  3.     private String bookName;  
  4.   
  5.     private int pages;  
  6.   
  7.     private double price;  
  8.   
  9.     private String author;  
  10.   
  11.     private String isbn;  
  12.   
  13.     public String getBookName() {  
  14.         return bookName;  
  15.     }  
  16.   
  17.     public void setBookName(String bookName) {  
  18.         this.bookName = bookName;  
  19.     }  
  20.   
  21.     public int getPages() {  
  22.         return pages;  
  23.     }  
  24.   
  25.     public void setPages(int pages) {  
  26.         this.pages = pages;  
  27.     }  
  28.   
  29.     public double getPrice() {  
  30.         return price;  
  31.     }  
  32.   
  33.     public void setPrice(double price) {  
  34.         this.price = price;  
  35.     }  
  36.   
  37.     public String getAuthor() {  
  38.         return author;  
  39.     }  
  40.   
  41.     public void setAuthor(String author) {  
  42.         this.author = author;  
  43.     }  
  44.   
  45.     public String getIsbn() {  
  46.         return isbn;  
  47.     }  
  48.   
  49.     public void setIsbn(String isbn) {  
  50.         this.isbn = isbn;  
  51.     }  
  52.   
  53. }  

然后写一个类专门用于将Book对象包装成XML格式:
[java]  view plain copy
  1. public class Formatter {  
  2.   
  3.     public String formatBook(Book book) {  
  4.         System.out.println("format begins");  
  5.         String result = "";  
  6.         result += "<book_name>" + book.getBookName() + "</book_name>\n";  
  7.         result += "<pages>" + book.getPages() + "</pages>\n";  
  8.         result += "<price>" + book.getPrice() + "</price>\n";  
  9.         result += "<author>" + book.getAuthor() + "</author>\n";  
  10.         result += "<isbn>" + book.getIsbn() + "</isbn>\n";  
  11.         System.out.println("format finished");  
  12.         return result;  
  13.     }  
  14.   
  15. }  
调用代码如下:
[java]  view plain copy
  1. public class Test {  
  2.       
  3.     public static void main(String[] args) throws Exception {  
  4.         Book book = new Book();  
  5.         book.setBookName("Thinking in Java");  
  6.         book.setPages(880);  
  7.         book.setPrice(68);  
  8.         book.setAuthor("Bruce Eckel");  
  9.         book.setIsbn("9787111213826");  
  10.         Formatter formatter = new Formatter();  
  11.         String result = formatter.formatBook(book);  
  12.         System.out.println(result);  
  13.     }  
  14.   
  15. }  

你写好了之后,迫不及待地开始运行,运行结果也完全符合你的期望。


项目经理看完后,对你非常满意,小伙效率很高的嘛!你也非常的得意。

不过两天之后,项目经理又找到了你,他说之前没有考虑到需要交互的客户端还包括手机设备,而手机设备都比较吃流量,用XML格式来传输太耗流量了,想最好能改成使用JSON格式传输。但是之前的XML格式也要保留,最好可以由客户端指定使用哪种格式。

你有些不开心,心里低估着,为什么一开始不考虑周全呢,现在又要改遗留代码。但对方毕竟是领导,你还是要服从命令的,于是你开始修改Formatter类:

[java]  view plain copy
  1. public class Formatter {  
  2.   
  3.     public static final int XML = 0;  
  4.   
  5.     public static final int JSON = 1;  
  6.   
  7.     public String formatBook(Book book, int format) {  
  8.         System.out.println("format begins");  
  9.         String result = "";  
  10.         if (format == XML) {  
  11.             result += "<book_name>" + book.getBookName() + "</book_name>\n";  
  12.             result += "<pages>" + book.getPages() + "</pages>\n";  
  13.             result += "<price>" + book.getPrice() + "</price>\n";  
  14.             result += "<author>" + book.getAuthor() + "</author>\n";  
  15.             result += "<isbn>" + book.getIsbn() + "</isbn>\n";  
  16.         } else if (format == JSON) {  
  17.             result += "{\n";  
  18.             result += "\"book_name\" : \"" + book.getBookName() + "\",\n";  
  19.             result += "\"pages\" : \"" + book.getPages() + "\",\n";  
  20.             result += "\"price\" : \"" + book.getPrice() + "\",\n";  
  21.             result += "\"author\" : \"" + book.getAuthor() + "\",\n";  
  22.             result += "\"isbn\" : \"" + book.getIsbn() + "\",\n";  
  23.             result += "}";  
  24.         }  
  25.         System.out.println("format finished");  
  26.         return result;  
  27.     }  
  28.   
  29. }  

调用代码如下:
[java]  view plain copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) throws Exception {  
  4.         Book book = new Book();  
  5.         book.setBookName("Thinking in Java");  
  6.         book.setPages(880);  
  7.         book.setPrice(68);  
  8.         book.setAuthor("Bruce Eckel");  
  9.         book.setIsbn("9787111213826");  
  10.         Formatter formatter = new Formatter();  
  11.         String result = formatter.formatBook(book, Formatter.XML);  
  12.         System.out.println(result);  
  13.         result = formatter.formatBook(book, Formatter.JSON);  
  14.         System.out.println(result);  
  15.     }  
  16.   
  17. }  
再次运行程序,得到了以下结果。


项目经理看到运行结果后开心地说:“太好了,这正是我想要的!” 

可是你这次却没有那么开心,你觉得代码已经有些混乱了,XML格式的逻辑和JSON格式的逻辑混淆在一起,非常不利于阅读,而且如果以后还需要扩展功能也会非常困难。好在传输格式一般也就XML和JSON了,应该不会再有什么扩展了,你这样安慰自己道。

但幻想总会被现实打破,“我最近听说有个YAML格式挺好玩的.......” 项目经理说道。这个时候你已经有想打人的冲动了!!!


很多时候就是这样,在公司里写的代码乱七八糟,质量极差,很大一部分原因就是因为需求变来变去。我们不断在原有代码基础上补充各种后续加入的情况,在一行行新增的if语句下面,我们的代码变得不堪入目。当然,我们作为程序员,对于需求这种东西没有太多的话语权,在这方面我们无能为力。但是我们可以尽量地把程序的架构设计好,让我们写出的代码更具有扩展性,这样就可以应对各种需求变更了。


下面你将要使用23种设计模式中的模板方法来改进以上程序。

首先将Formatter中的代码进行修改,如下所示:

[java]  view plain copy
  1. public abstract class Formatter {  
  2.   
  3.     public String formatBook(Book book, int format) {  
  4.         beforeFormat();  
  5.         String result = formating(book);  
  6.         afterFormat();  
  7.         return result;  
  8.     }  
  9.   
  10.     protected void beforeFormat() {  
  11.         System.out.println("format begins");  
  12.     }  
  13.   
  14.     protected abstract String formating(Book book);  
  15.   
  16.     protected void afterFormat() {  
  17.         System.out.println("format finished");  
  18.     }  
  19.   
  20. }  
你会发现format_book方法只有四步,第一步调用before_format,去打印格式转换前的日志。第二步调用formating,这个方法是个抽象方法,用于处理具体的转换逻辑,因此每一个继承自Formatter的子类都需要重写此方法,来实现各自的转换逻辑。第三步调用after_format,去打印格式转换后的日志。第四步返回result。由于类中存在了抽象方法,我们也就需要把Formatter声明成抽象类。

然后要定义专门的子类来处理每种传输格式的具体逻辑,这样不同传输格式的逻辑可以从一个方法里分离开,明显便于阅读和理解。

定义类XMLFormatter继承自Formatter,里面加入处理XML格式的具体逻辑:

[java]  view plain copy
  1. public class XMLFormatter extends Formatter {  
  2.   
  3.     @Override  
  4.     protected String formating(Book book) {  
  5.         String result = "";  
  6.         result += "<book_name>" + book.getBookName() + "</book_name>\n";  
  7.         result += "<pages>" + book.getPages() + "</pages>\n";  
  8.         result += "<price>" + book.getPrice() + "</price>\n";  
  9.         result += "<author>" + book.getAuthor() + "</author>\n";  
  10.         result += "<isbn>" + book.getIsbn() + "</isbn>\n";  
  11.         return result;  
  12.     }  
  13.   
  14. }  

定义类JSONFormatter继承自Formatter,里面加入处理JSON格式的具体逻辑:
[java]  view plain copy
  1. public class JSONFormatter extends Formatter {  
  2.   
  3.     @Override  
  4.     protected String formating(Book book) {  
  5.         String result = "";  
  6.         result += "{\n";  
  7.         result += "\"book_name\" : \"" + book.getBookName() + "\",\n";  
  8.         result += "\"pages\" : \"" + book.getPages() + "\",\n";  
  9.         result += "\"price\" : \"" + book.getPrice() + "\",\n";  
  10.         result += "\"author\" : \"" + book.getAuthor() + "\",\n";  
  11.         result += "\"isbn\" : \"" + book.getIsbn() + "\",\n";  
  12.         result += "}";  
  13.         return result;  
  14.     }  
  15.   
  16. }  

最后调用代码如下:

[java]  view plain copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) throws Exception {  
  4.         Book book = new Book();  
  5.         book.setBookName("Thinking in Java");  
  6.         book.setPages(880);  
  7.         book.setPrice(68);  
  8.         book.setAuthor("Bruce Eckel");  
  9.         book.setIsbn("9787111213826");  
  10.         XMLFormatter xmlFormatter = new XMLFormatter();  
  11.         String result = xmlFormatter.formatBook(book);  
  12.         System.out.println(result);  
  13.         JSONFormatter jsonFormatter = new JSONFormatter();  
  14.         result = jsonFormatter.formatBook(book);  
  15.         System.out.println(result);  
  16.     }  
  17.   
  18. }  

运行之后,你会发现运行结果和修改前代码的运行结果完全相同。但是使用模板方法之后,代码的可读性有了很大的提高,因为处理格式转换的代码都放到了各自的类当中,而不是全部塞进一个方法中。并且在扩展性上也有了很大的提升,比如你开始感兴趣项目经理说的YAML格式了。

定义类YAMLFormatter继承自Formatter,里面加入处理YAML格式的具体逻辑:

[java]  view plain copy
  1. public class YAMLFormatter extends Formatter {  
  2.   
  3.     @Override  
  4.     protected String formating(Book book) {  
  5.         String result = "";  
  6.         result += "book_name: " + book.getBookName() + "\n";  
  7.         result += "pages: " + book.getPages() + "\n";  
  8.         result += "price: " + book.getPrice() + "\n";  
  9.         result += "author: " + book.getAuthor() + "\n";  
  10.         result += "isbn: " + book.getIsbn() + "\n";  
  11.         return result;  
  12.     }  
  13.   
  14. }  

调用代码只需要加入:
[java]  view plain copy
  1. YAMLFormatter yamlFormatter = new YAMLFormatter();  
  2. String result = yamlFormatter.formatBook(book);  
  3. System.out.println(result);  

好了,令人头疼的YAML格式就这样被支持了,只需要在调用的时候决定是实例化XMLFormatter,JSONFormatter还是YAMLFormatter,就可以按照相应的规格进行格式转换了。而且整体的代码很有条理,看起来也很舒心。这个时候,你会轻松地向项目经理调侃一句,还有需要支持的格式吗?


模板方法: 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值