模板方法

来源:互联网 发布:淘宝林珊珊店铺头像 编辑:程序博客网 时间:2024/06/05 00:54

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

模板方法设计模式的意图:通常我们会遇到这样的一个问题:我们知道一个算法所需的关键步骤,并确定了这些步骤的执行顺序。但是某些步骤的具体实现是未知的,或者说某些步骤的实现与具体的环境相关。
模板方法模式把我们不知道具体实现的步骤封装成抽象方法,提供一个按正确顺序调用它们的具体方法(这些具体方法统称为“模板方法”),这样构成一个抽象基类。子类通过继承这个抽象基类去实现各个步骤的抽象方法,而工作流程却由父类控制。


以下转自郭霖的博客: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,就可以按照相应的规格进行格式转换了。而且整体的代码很有条理,看起来也很舒心。这个时候,你会轻松地向项目经理调侃一句,还有需要支持的格式吗?

0 0
原创粉丝点击