一. 核心思想
对象参数比较多, 部分参数非必传, 初始化对象比较复杂时使用.
例如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();
总结: 具体什么时候使用自己把握, 写法也是可以变化的, 不要定性思维.
网友评论