Java设计模式透析之——模板方法

来源:互联网 发布:千方百剂软件 编辑:程序博客网 时间:2024/05/17 04:10

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

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

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

Book对象代码如下:


public class Book {

    privateString name;
    privateString author;
    privateString isbn;
    private intpages;
    privatedouble price;
   

    publicString getName() {
       returnname;
    }

    public voidsetName(String name) {
       this.name =name;
    }

    publicString getAuthor() {
       returnauthor;
    }

    public voidsetAuthor(String author) {
       this.author= author;
    }

    publicString getIsbn() {
       returnisbn;
    }

    public voidsetIsbn(String isbnString) {
       this.isbn =isbnString;
    }

    public intgetPages() {
       returnpages;
    }

    public voidsetPages(int pages) {
       this.pages =pages;
    }

    publicdouble getPrice() {
       returnprice;
    }

    public voidsetPrice(double price) {
       this.price =price;
    }
}

然后写一个类专门用于将Book对象包装成XML格式:

public class Formatter {

   
    publicString formatBook(Book book) {
      System.out.println("format begin:");
       Stringresult = "";
       result += ""+ book.getName() + "\n";
       result += ""+ book.getAuthor() + "\n";
       result += ""+book.getIsbn() + "\n";
       result += ""+book.getPages() + "\n";
       result += ""+book.getPrice() + "\n";
      System.out.println("format finished");
       returnresult;
    }

}

最后再来一个测试方法:


public class Test {

   
    publicstatic void main(String[] args) {
       // TODOAuto-generated method stub

       Book book =new Book();
      book.setName("Android Develop");
      book.setAuthor("Duandian");
      book.setIsbn("XN110");
      book.setPages(1000);
      book.setPrice(65.5);
      
       Formatterformatter = new Formatter();
       Stringresult = formatter.formatBook(book);
      
      System.out.println(result);
    }

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

format begin:
format finished
Android Develop
Duandian
XN110
1000
65.5

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

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

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

public class Formatter {

    publicstatic final int XML = 0;

    publicstatic final int JSON = 1;

    publicString formatBook(Book book, int format) {
      System.out.println("format begins");
       Stringresult = "";
       if (format== XML) {
          result += ""+ book.getBookName() + "\n";
          result += ""+ book.getPages() + "\n";
          result += ""+ book.getPrice() + "\n";
          result += ""+ book.getAuthor() + "\n";
          result += ""+ book.getIsbn() + "\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");
       returnresult;
    }

}

测试代码:

public class Test {

    publicstatic void main(String[] args) throws Exception {
       Book book =new Book();
      book.setName("Android Develop");
      book.setAuthor("Duandian");
      book.setIsbn("XN110");
      book.setPages(1000);
      book.setPrice(65.5);
       Formatterformatter = new Formatter();
       Stringresult = formatter.formatBook(book, Formatter.XML);
      System.out.println(result);
       result =formatter.formatBook(book, Formatter.JSON);
      System.out.println(result);
    }

}

再次运行程序,得到了以下结果。

format begin:
format finished
Android Develop
Duandian
XN110
1000
65.5

format begin:
format finished
{
"book_name" : "Android Develop",
"author" : " Duandian",
"isbn" : " XN110",
"page" : " 1000",
"price" : " 65.5",
}

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

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

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

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

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

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

public abstract class FormatFactory {

    publicString  FormatBook(Book book) {
   
      beforeFormat();
       Stringresult = formating(book);
      afterFormat();
      
       returnresult;
    }

    protectedabstract String formating(Book book);

    protectedvoid afterFormat() {
       // TODOAuto-generated method stub
      System.out.println("Format  finished");
    }

    protectedvoid beforeFormat() {
       // TODOAuto-generated method stub
      System.out.println("Format begin:");
    }
}

你会发现format_book方法只有四步,第一步调用before_format,去打印格式转换前的日志。第二步调用formating,这个方法是个抽象方法,用于处理具体的转换逻辑,因此每一个继承自Formatter的子类都需要重写此方法,来实现各自的转换逻辑。第三步调用after_format,去打印格式转换后的日志。第四步返回result。由于类中存在了抽象方法,我们也就需要把Formatter声明成抽象类。

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

定义类XmlFormat 继承自Formatter,里面加入处理XML格式的具体逻辑:
public class XmlFormat extends FormatFactory {

   @Override
    protectedString formating(Book book) {
       // TODOAuto-generated method stub
       Stringresult = "";
       result += ""+ book.getName() + "\n";
       result += ""+ book.getAuthor() + "\n";
       result += ""+book.getIsbn() + "\n";
       result += ""+book.getPages() + "\n";
       result += ""+book.getPrice() + "\n";
       returnresult;
    }

}

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


public class JsonFormat extends FormatFactory {

   @Override
    protectedString formating(Book book) {
       // TODOAuto-generated method stub
       Stringresult = "";
       result+="{\n";
       result +="\"book_name\" : \"" + book.getName() +"\",\n"; 
       result+="\"author\" : \" "+ book.getAuthor() + "\",\n";
       result+="\"isbn\" : \" "+book.getIsbn() + "\",\n";
       result+="\"page\" : \" "+ book.getPages() +"\",\n";
       result +="\"price\" : \" "+ book.getPrice() +"\",\n";
       result +="}";
       returnresult;
    }

}
测试代码如下:


public class Test {

   
    publicstatic void main(String[] args) {
       // TODOAuto-generated method stub

       Book book =new Book();
      book.setName("Android Develop");
      book.setAuthor("Duandian");
      book.setIsbn("XN110");
      book.setPages(1000);
      book.setPrice(65.5);
      
       XmlFormatxmlFormat = new XmlFormat();
       Stringresult = xmlFormat.FormatBook(book);
      System.out.println(result);
      
       JsonFormatjsonFormat  = new JsonFormat();
       Stringresult1 = jsonFormat.FormatBook(book);
      System.out.println(result1);
      
    }

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

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


public class OtherFormat extends FormatFactory {

   @Override
    protectedString formating(Book book) {
       // TODOAuto-generated method stub
       Stringresult = ""; 
       result += "book_name: " + book.getName() +"\n"; 
       result += "pages: " + book.getPages() +"\n"; 
       result += "price: " + book.getPrice() +"\n"; 
       result += "author: " + book.getAuthor() +"\n"; 
       result += "isbn: " + book.getIsbn() + "\n"; 
       return result; 
    }

}
然后在测试代码中加入:

OtherFormat otherFormat = new OtherFormat();

System.out.println(otherFormat.FormatBook(book));
Ok,到此大功告成,以后再有什么格式直接加就行!

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

转自:http://blog.csdn.net/guolin_blog/article/details/8744002



0 0
原创粉丝点击