美文网首页
Android设计模式---Builder设计模式

Android设计模式---Builder设计模式

作者: liys_android | 来源:发表于2019-08-23 18:13 被阅读0次
一. 核心思想

对象参数比较多, 部分参数非必传, 初始化对象比较复杂时使用.
例如OkHttp中, OkHttpClient初始化过程.

二, 简单实现
public class UserInfo {
    private String name; //必传
    private int age; //
    private  int count;

    public UserInfo(Bulder bulder){
        name = bulder.name;
        age = bulder.age;
        count = bulder.count;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public static class Bulder{
        private String name; //必传
        private int age; //
        private  int count;

        public Bulder(String name){
            this.name = name;
        }

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

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

        public Bulder setCount(int count) {
            this.count = count;
            return this;
        }

        public UserInfo bulder(){
            UserInfo userInfo = new UserInfo(this);
            return userInfo;
        }
    }
}

使用

UserInfo userInfo = new UserInfo.Bulder("liys")
                                        .setAge(27)
                                        .setCount(100)
                                        .bulder();

总结: 具体什么时候使用自己把握, 写法也是可以变化的, 不要定性思维.

相关文章

网友评论

      本文标题:Android设计模式---Builder设计模式

      本文链接:https://www.haomeiwen.com/subject/afaipqtx.html