构建者模式简单实现

使用多个简单的对象一步一步构建成一个复杂的对象;
优点:当内部数据过于复杂的时候,可以非常方便的构建出我们想要的对象,并且不是所有的参数我们都需要进行传递;
缺点:代码会有冗余

public class House {
    private double height;
    private double weight;
    private String color;

    public House(Builder builder) {
        this.height = builder.height;
        this.weight = builder.weight;
        this.color = builder.color;
    }

    public static final class Builder{
        double height;
        double weight;
        String color;

        public Builder addHeight(double height){
            this.height = height;
            return this;
        }
        public Builder addWeight(double weight){
            this.weight = weight;
            return this;
        }
        public Builder addColor(String color){
            this.color = color;
            return this;
        }

        public Builder(){
            this.height = 100;
            this.weight = 100;
            this.color = "red";
        }
        public House build(){
            return new House(this);
        }
    }

    @Override
    public String toString() {
        return "House{" +
                "height=" + height +
                ", weight=" + weight +
                ", color='" + color + '\'' +
                '}';
    }
}


private void gouzaozhe() {
		//这里Builder后可以自由添加属性
        House house = new House.Builder().build();
        System.out.println(house);
        //比如
         House house = new House.Builder().addHeight(1).build();
    }

你可能感兴趣的:(java,开发语言,建造者模式)