码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-06-28 14:23:28      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:black   details   track   .net   tool   out   alt   ref   res   

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

项目经理告诉你,今天想在server端添加一个新功能。希望写一个方法。能对Book对象进行处理。将Book对象的全部字段以XML格式进行包装。这样以后能够方便与client进行交互。而且在包装開始前和结束后要打印日志,这样方便调试和问题定位。

没问题!你认为这个功能简直是小菜一碟,很自信地開始写起代码。

Book对象代码例如以下:

[java] view plaincopy
  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 plaincopy
  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.     }  

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

标签:black   details   track   .net   tool   out   alt   ref   res   

原文地址:http://www.cnblogs.com/yxysuanfa/p/7089308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!