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


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

    项目经理告诉你,今天想在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> ";  
    7.         result += "<pages>" + book.getPages() + "</pages> ";  
    8.         result += "<price>" + book.getPrice() + "</price> ";  
    9.         result += "<author>" + book.getAuthor() + "</author> ";  
    10.         result += "<isbn>" + book.getIsbn() + "</isbn> ";  
    11.         System.out.println("format finished");  
    12.         return result;  
    13.     }  
    14. 相关阅读:
      页面跳转时,统计数据丢失问题探讨
      JSBridge 知识点
      数据埋点 知识点
      ES6 模块与 CommonJS 模块的差异
      koa 学习资料
      浏览器渲染流程
      Object.create() 的含义:从一个实例对象,生成另一个实例对象
      this、new,容易混淆的地方
      为什么js 的constructor中是无限循环嵌套:Foo.__proto__.constructor.prototype.constructor.prototype.constructor.prototype.xxx ?
      实例对象与 new 命令
    15. 原文地址:https://www.cnblogs.com/yxysuanfa/p/7089308.html
Copyright © 2020-2023  润新知