android Builder模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014476720/article/details/81632445
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;
    }

猜你喜欢

转载自blog.csdn.net/u014476720/article/details/81632445