建造者模式

目录

使用场景

当一个类的构造函数需要四个及以上的参数,且某些参数可为空,可以考虑选用建造者模式。

实现

假如现在有个pdf的配置类其中有尺寸、标题、作者、颜色等字段,其中作者和颜色是可以不传入的但是尺寸和标题是必须传入的,并且尺寸是有枚举值的,那么可以进行以下实现。

public class PdfConfig {
    public static final String A3 = "A3";
    public static final String A4 = "A4";
    /**
     * 尺寸
     */
    private final String specification;

    /**
     * 标题
     */
    private final String title;

    /**
     * 作者
     */
    private final String author;

    /**
     * 颜色
     */
    private String color;

    private PdfConfig(Builder builder) {
        this.specification = builder.specification;
        this.title = builder.title;
        this.author = builder.author;
        this.color = builder.color;
    }

    @Override
    public String toString() {
        return "PdfConfig{" +
                "specification='" + specification + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", color='" + color + '\'' +
                '}';
    }

    public static class Builder{

        private String specification;
        private String title;
        private String author;
        private String color;

        public Builder setSpecification(String sf){
            this.specification = sf;
            return this;
        }

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

        public Builder setAuthor(String author){
            this.author = author;
            return this;
        }

        public Builder setColor(String color){
            this.color = color;
            return this;
        }

        public PdfConfig build(){
            if (!A3.equals(specification) && !A4.equals(specification)){
                throw new RuntimeException("尺寸不合规");
            }else if (title == null){
                throw new RuntimeException("请输入标题");
            }
            return new PdfConfig(this);
        }
    }
}

下面是其使用过程,这样就相比不断地使用对象进行set或者使用构造函数传入固定参数而言,"优雅得多"

public class PdfConfigDemo {
    public static void main(String[] args) {
        PdfConfig pdfConfig = new PdfConfig.Builder()
                .setSpecification(PdfConfig.A3)
                .setAuthor("eacape")
                .setTitle("hello")
                .build();
        System.out.printf(pdfConfig.toString());

    }
}

在一些中间件和java api中,建造者模式还是比较常见的,例如lombok的@Builder和StringBuilder类

你可能感兴趣的