1. 程式人生 > >android Builder模式

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;
    }