android Builder模式

public class UserInfo {
    private String name;
    private String height;
    private int age;
    private int year;

    public String getName() {
        return name;
    }

    public String getHeight() {
        return height;
    }

    public int getAge() {
        return age;
    }

    public int getYear() {
        return year;
    }

    @Override
    public String toString() {
        return name+"_"+height+"_"+age+"_"+year;
    }

    private UserInfo(Builder builder) {
        this.name = builder.name;
        this.height = builder.height;
        this.age = builder.age;
        this.year = builder.year;
    }

    public static class Builder {
        private String name;
        private String height;
        private int age;
        private int year;

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

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

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public Builder year(int year) {
            this.year = year;
            return this;
        }

        public UserInfo builder() {
            return new UserInfo(this);
        }
    }
}

使用

   UserInfo userInfo = new UserInfo.Builder()
                .name("kawa")
                .height("212")
                .age(12)
                .year(21)
                .builder();
        LogUtils.e(userInfo.toString());

使用Builder模式赋值可以很清晰的知道自己传入的值是什么,如果是使用构造函数传入值的话,不知道当前的值对应是啥,值一多就容易混淆,

    public UserInfo(String name, String height, int age, int year) {
        this.name = name;
        this.height = height;
        this.age = age;
        this.year = year;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值