今天你还是像往常一样来上班,一如既往地开始了你的编程工作。
项目经理告诉你,今天想在服务器端增加一个新功能,希望写一个方法,能对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);
- }
- }
本文地址 : http://www.fengfly.com/plus/view-215083-1.html
标签: java Template Method |