Builder模式功能是组装复杂的实例,重点关注过程,一共存在3个角色:Bulider(建造者)、 ConcreteBuilder(具体建造者)、 Dirctor(监工)
使用Builder模式编写文档,定义Builder的子类:
- TextBuilder: 使用纯文本编写文档
- HTMLBuilder: 使用HTML编写文档
UML
示例代码
Builder
1 2 3 4 5
| public abstract class Builder { protected abstract void makeTitle(String title); protected abstract void makeString(String str); protected abstract void close(); }
|
TextBuilder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class TextBuilder extends Builder{
private StringBuffer buffer = new StringBuffer();
@Override protected void makeTitle(String title) { buffer.append("==============================\n"); buffer.append("『" + title + "』\n"); buffer.append("\n"); }
@Override protected void makeString(String str) { buffer.append('■' + str + "\n"); buffer.append("\n"); }
@Override protected void close() { buffer.append("==============================\n"); }
public String getResult() { return buffer.toString(); } }
|
HTMLBuilder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class HTMLBuilder extends Builder {
private String filename; private PrintWriter writer;
@Override protected void makeTitle(String title) { filename = title + ".html"; try { writer = new PrintWriter(new FileWriter(filename)); } catch (IOException e) { e.printStackTrace(); } writer.println("<html><head><title>" + title + "</title></head><body>"); writer.println("<h1>" + title + "</h1>"); }
@Override protected void makeString(String str) { writer.println("<p>" + str + "</p>"); }
@Override protected void close() { writer.println("</body></html>"); writer.close(); }
public String getResult() { return filename; } }
|
Director
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Director {
private Builder builder;
public Director(Builder builder) { this.builder = builder; }
public void construct() { builder.makeTitle("Greeting"); builder.makeString("从早上到下午"); builder.close(); } }
|
Main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Main { public static void main(String[] args) {
TextBuilder textBuilder = new TextBuilder(); Director director = new Director(textBuilder); director.construct(); System.out.println(textBuilder.getResult());
HTMLBuilder htmlBuilder = new HTMLBuilder(); director = new Director(htmlBuilder); director.construct(); System.out.println(htmlBuilder.getResult());
} }
|
Builder需要有相同的生产过程,且有部件需要生产,而工厂模式一般没有,更侧重生产结果。
抽象工厂通过不同的构建过程生成不同的对象,而Builder模式通过相同的构建过程生成不同的对象。
builder 也是一个高层建筑,但是他和Abstract Factory侧重点不同,Abstract Factory侧重于创建东西的结果,而builder侧重的是创建东西的过程。当你需要做一系列有序的工作来完成创建一个对象时 builder就派上用场啦