举个例子,要按照不同的方式生成文本,有纯文本和html形式,使用建造者模式,将实现细节分别实现在具体的builder里。
话不多说,直接上代码
image.png

/**
 * 声明一个编写文档的方法
 */
public abstract class Builder {
    public abstract void makeTitle(String title);

    public abstract void makeString(String string);

    public abstract void makeItems(String[] items);

    public abstract void close();
}
/**
 * 将具体的builder实现过程写在这里
 */
public class Director {
    private Builder builder;

    public Director(Builder builder) {
        this.builder = builder;
    }

    public void construct() {
        builder.makeTitle("Greeting");
        builder.makeString("从早上至下午");
        builder.makeItems(new String[]{
                "早上好",
                "早安"
        });
        builder.makeString("晚上");
        builder.makeItems(new String[]{
                "晚上好",
                "晚安",
                "再见"
        });
        builder.close();
    }
}

接下来分别由HtmlBuilder实现html的类型以及TextBuilder实现纯文本类型

public class HtmlBuilder extends Builder {
    private String fileName;
    private PrintWriter printWriter;

    @Override
    public void makeTitle(String title) {
        fileName = title + ".html";
        try {
            printWriter = new PrintWriter(new FileWriter(fileName));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        printWriter.println("<html><head><title>" + title + "</title></head><body>");
        printWriter.println("<h1>" + title + "</h1>");
    }

    @Override
    public void makeString(String string) {
        printWriter.println("<p>" + string + "</p>");
    }

    @Override
    public void makeItems(String[] items) {
        printWriter.println("<ul>");
        for (String item : items) {
            printWriter.println("<li>" + item + "</li>");
        }
        printWriter.println("</ul>");
    }

    @Override
    public void close() {
        printWriter.println("</body></html>");
        printWriter.close();
    }

    public String getResult() {
        return fileName;
    }
}
public class TextBuilder extends Builder {
    private StringBuilder stringBuilder = new StringBuilder();

    @Override
    public void makeTitle(String title) {
        stringBuilder.append("============================\n");
        stringBuilder.append("[").append(title).append("]\n");
        stringBuilder.append("\n");
    }

    @Override
    public void makeString(String string) {
        stringBuilder.append("[]").append(string).append("\n");
        stringBuilder.append("\n");
    }

    @Override
    public void makeItems(String[] items) {
        for (String item : items) {
            stringBuilder.append(" -").append(item).append("\n");
        }
        stringBuilder.append("\n");
    }

    @Override
    public void close() {
        stringBuilder.append("=======================================\n");
    }

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

最后由客户端调用

    public static void main(String[] args) {
        if (args.length != 1) {
            usage();
            System.exit(0);
        }
        if (args[0].equals("plain")) {
            TextBuilder textBuilder = new TextBuilder();
            Director director = new Director(textBuilder);
            director.construct();
            String result = textBuilder.getResult();
            System.out.println(result);
        }
        if (args[0].equals("html")) {
            HtmlBuilder htmlBuilder = new HtmlBuilder();
            Director director = new Director(htmlBuilder);
            director.construct();
            String fileName = htmlBuilder.getResult();
            System.out.println(fileName);
        } else {
            usage();
            System.exit(0);
        }
    }

    public static void usage() {
        System.out.println("Usage:          Java Main plain   编写纯文本文档");
        System.out.println("Usage:          Java Main html    编写HTML文档");
    }

还有一个我们常见的builder模式,比如

    List<String> builderList = ImmutableList.<String>builder().add("123").build();

类似的还有Lombok的@Builder注解标注的DO类,链式调用之后进行创建。实际上是对上面的builder模式的精简,只有一种产品,建造方式只是赋值。