leftso 462 0 2018-04-01 10:30:13

引言

以前我们看过工厂和抽象工厂模式。这些模式可以达到其目的,并且可以非常有用,但是有一些用例我们必须创建一个非常复杂的对象,并且创建它需要不同的步骤,每个步骤都需要不同的操作。在这种情况下,构建器模式可能非常有用。

什么是构建模式

构建器设计模式是一种创建式设计模式,可用于逐步创建复杂对象。

假设我们有一个具有很多依赖关系的对象,并且为了获得这些依赖关系中的每一个,必须发布一些特定的动作。
在这种情况下,我们可以使用构建器模式
  • 封装在一个单独的Builder 对象中创建和组装一个复杂对象的各个部分  。
  • 将对象创建委托给  Builder 对象而不是直接创建对象。

想象一下后端系统需要编写和发送邮件的场景。
创建电子邮件可能是一个复杂的过程。您必须指定标题,设置收件人,添加问候语添加结束语句。您可能也想使用小胡子。有多种选择。

有一个类需要创建一个电子邮件的所有行动可能会使我们的课程臃肿和松散的原始目的。

所以我们将从负责发送电子邮件的班级开始。

public class Email {

    private final String title;
    private final String recipients;
    private final String message;

    public Email(String title, String recipients, String message) {
        this.title = title;
        this.recipients = recipients;
        this.message = message;
    }

    public String getTitle() {
        return title;
    }

    public String getRecipients() {
        return recipients;
    }

    public String getMessage() {
        return message;
    }

    public void send() {

    }
}

正如你所看到的,这个类只包含三个字符串字段,并且没有额外的处理。因此,我们将创建一个构建器类,它将处理邮件格式,收件人表示和创建电子邮件类。
public class EmailBuilder {

    private Set recipients = new HashSet();
    private String title;
    private String greeting;
    private String mainText;
    private String closing;

    public EmailBuilder addRecipient(String recipient) {
        this.recipients.add(recipient);
        return this;
    }

    public EmailBuilder removeRecipient(String recipient) {
        this.recipients.remove(recipient);
        return this;
    }

    public EmailBuilder setTitle(String title) {
        this.title = title;
        return this;
    }

    public EmailBuilder setGreeting(String greeting) {
        this.greeting = greeting;
        return this;
    }

    public EmailBuilder setMainText(String mainText) {
        this.mainText = mainText;
        return this;
    }

    public EmailBuilder setClosing(String closing) {
        this.closing = closing;
        return this;
    }

    public Email create() {

        String message = greeting+"\n"+mainText+"\n"+closing;
        String recipientSection = commaSeparatedRecipients();

        return new Email(title,recipientSection,message);
    }

    private String commaSeparatedRecipients() {

        StringBuilder sb = new StringBuilder();
        for(String recipient:recipients) {
            sb.append(",").append(recipient);
        }

        return sb.toString().replaceFirst(",","");
    }

}

接下来是使电子邮件创建更加严格的步骤,以便只有通过EmailBuilder才能创建电子邮件。
public class Email {

    private final String title;
    private final String recipients;
    private final String message;

    private Email(String title, String recipients, String message) {
        this.title = title;
        this.recipients = recipients;
        this.message = message;
    }

    public String getTitle() {
        return title;
    }

    public String getRecipients() {
        return recipients;
    }

    public String getMessage() {
        return message;
    }

    public void send() {

    }

    public static class EmailBuilder {

        private Set recipients = new HashSet();
        private String title;
        private String greeting;
        private String mainText;
        private String closing;

        public EmailBuilder addRecipient(String recipient) {
            this.recipients.add(recipient);
            return this;
        }

        public EmailBuilder removeRecipient(String recipient) {
            this.recipients.remove(recipient);
            return this;
        }

        public EmailBuilder setTitle(String title) {
            this.title = title;
            return this;
        }

        public EmailBuilder setGreeting(String greeting) {
            this.greeting = greeting;
            return this;
        }

        public EmailBuilder setMainText(String mainText) {
            this.mainText = mainText;
            return this;
        }

        public EmailBuilder setClosing(String closing) {
            this.closing = closing;
            return this;
        }

        public Email build() {

            String message = greeting+"\n"+mainText+"\n"+closing;
            String recipientSection = commaSeparatedRecipients();

            return new Email(title,recipientSection,message);
        }

        private String commaSeparatedRecipients() {

            StringBuilder sb = new StringBuilder();
            for(String recipient:recipients) {
                sb.append(",").append(recipient);
            }

            return sb.toString().replaceFirst(",","");
        }

    }
}

使用构建器模式创建电子邮件的最终结果就是这样。
Email email = new Email.EmailBuilder()
    .addRecipient("john@Doe.com")
    .setMainText("Check the builder pattern")
    .setGreeting("Hi John!")
    .setClosing("Regards")
    .setTitle("Builder pattern resources")
    .build();
通过使用构建器模式进行总结,我们能够创建一个复杂的对象及其复杂的部分。