Builder模式

Posted xiaoyaomianbiren

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Builder模式相关的知识,希望对你有一定的参考价值。

  builer英文名原意为建造者,在Builder模式中,主要有Builer(建造者),concreteBuilder(具体的建造者),Directer(监工)以及Client(使用者),其中Builder定义了各种建造的方法,并作为Directer的字段,并在Directer中定义了builder的方法执行顺序以及执行时所需要的参数,ConcrereBuilder则实现了Builder中的方法,下面通过案例说明:

  用Builder模式编写文档,文档中含有一个标题,含有几个字符串,含有条目项目。

  首先定义Builder

 1 package framework;
 2 
 3 public interface Builder {
 4     public abstract void makeTitle(String title);
 5 
 6     public abstract void makeString(String str);
 7 
 8     public abstract void makeItems(String[] items);
 9 
10     public abstract void close();
11 }

然后是Directer类

 1 package framework;
 2 
 3 public class Director {
 4     private Builder builder;
 5 
 6     public Director(Builder builder) {
 7         this.builder = builder;
 8     }
 9 
10     public void construct() {
11         builder.makeTitle("Greeting");
12         builder.makeString("从早上到下午");
13         builder.makeItems(new String[] { "早上好", "下午好", });
14         builder.makeString("晚上");
15         builder.makeItems(new String[] { "晚上好", "晚安", "再见", });
16         builder.close();
17     }
18 }

然后是实现了Builder的两个子类,这两个子类充当concreteBUilder角色

package concrete;

import framework.Builder;

public class htmlBuilder implements Builder {
    private StringBuffer buffer = new StringBuffer();

    @Override
    public void makeTitle(String title) {
        buffer.append("========================================
");
        buffer.append("[" + title + "]
");
        buffer.append("
");
    }

    @Override
    public void makeString(String str) {
        buffer.append("@" + str + ":
");
        buffer.append("
");
    }

    @Override
    public void makeItems(String[] items) {
        int length = items.length;
        for (int i = 0; i < length; i++) {
            buffer.append("    ." + items[i] + "
");
        }
        buffer.append("
");
    }

    @Override
    public void close() {
        buffer.append("===========================================
");
    }

    public String getResult() {
        return buffer.toString();
    }

}
 1 package concrete;
 2 
 3 import java.io.FileWriter;
 4 import java.io.IOException;
 5 import java.io.PrintWriter;
 6 
 7 import framework.Builder;
 8 
 9 public class TextBuilder implements Builder {
10     private String filename;
11 
12     private PrintWriter writer;
13 
14     @Override
15     public void makeTitle(String title) {
16         filename = title + ".html";
17         try {
18             writer = new PrintWriter(new FileWriter(filename));
19         } catch (IOException e) {
20 
21             // Auto-generated catch block
22             e.printStackTrace();
23 
24         }
25         writer.println("<html><head><title>" + title + "</title></head><body>");
26         writer.println("<h1>" + title + "</h1>");
27     }
28 
29     @Override
30     public void makeString(String str) {
31         writer.println("<p>" + str + "</p>");
32     }
33 
34     @Override
35     public void makeItems(String[] items) {
36         writer.println("<ul>");
37         for (int i = 0; i < items.length; i++) {
38             writer.println("<li>" + items[i] + "</li>");
39         }
40         writer.println("</ul>");
41     }
42 
43     @Override
44     public void close() {
45         writer.println("</body></html>");
46         writer.close();
47 
48     }
49 
50     public String getResult() {
51         return filename;
52     }
53 }

最后是Main程序入口,充当Client角色

 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         if (args.length != 1) {
 5             System.out.println("哈哈哈哈");
 6             System.exit(0);
 7         }
 8         if (args[0].equals("plain")) {
 9             TextBuilder textBuilder = new TextBuilder();
10             Director director = new Director(textBuilder);
11             director.construct();
12             String result = textBuilder.getResult();
13             System.out.println(result);
14         } else if (args[0].equals("html")) {
15             HTMLBuilder htmlBuilder = new HTMLBuilder();
16             Director director = new Director(htmlBuilder);
17             director.construct();
18             String result = htmlBuilder.getResult();
19             System.out.println(result + "文件编写完成");
20         } else {
21             System.exit(0);
22             ;
23         }
24     }
25 
26 }

当我们需要编写其他类型的文档时并且文档内容不变时,并不需要对Directer和Builder修改,仅仅定义一个子类继承Builder就可以了,这里的Directer与Builder就可以作为组件重复使用,这就是Builder模式的优点。

以上是关于Builder模式的主要内容,如果未能解决你的问题,请参考以下文章

Builder设计模式,模板设计模式,Adapter设计模式笔记

builder模式-积木系列

变种 Builder 模式:优雅的对象构建方式

[05]Go设计模式:建造者模式(Builder Pattern)

设计模式Builder模式

23种设计模式之建造者模式代码实例