构建者模式简单实现

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

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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值