java中使用Builder模式构建多个参数的构造器

public class BeanEntity
{
    private int variable1;//必选参数
    private int variable2;//必选参数
    private int variable3;//可选参数
    private int variable4;//可选参数

    private BeanEntity(Builder builder){
        this.variable1 = builder.variable1;
        this.variable2 = builder.variable2;
        this.variable3 = builder.variable3;
        this.variable4 = builder.variable4;
    }

    public static class Builder{
        private int variable1;
        private int variable2;
        private int variable3;
        private int variable4;

        public Builder(int variable1, int variable2){
            this.variable1 = variable1;
            this.variable2 = variable2;
        }

        public Builder setVariable3(int variable3){
            this.variable3= variable3;
            return this;
        }
        public Builder setVariable4(int variable4){
            this.variable4= variable4;
            return this;
        }

        public BeanEntity build(){
            return new BeanEntity(this);
        }
    }
}

使用

 BeanEntity entity = new BeanEntity.Builder(100, 200)
             .setVariable3(300)
             .setVariable4(400)
             .build();

你可能感兴趣的:(java)