优点:易扩展,使用方便灵活配置参数。例如AlertDialog、Retrofit ...
缺点:内部变化复杂,会有很多的建造类。
Person person =new Person.PersonBuilder()
.buildAge(10)
.buildLike("watch TV")
.buildName("CC")
.build();
/**
* Builder 构建模式
*/
public class Person {
private Stringname;
private Stringlike;
private int age;
private Stringkind;
private Person(String name, String like, int age, String kind) {
this.name = name;
this.like = like;
this.age = age;
this.kind = kind;
}
public Person(PersonBuilder builder) {
this.name = builder.name;
this.like = builder.like;
this.age = builder.age;
this.kind = builder.kind;
}
public Person() {
}
protected void setName(String name) {
this.name = name;
}
protected void setLike(String like) {
this.like = like;
}
protected void setAge(int age) {
this.age = age;
}
protected void setKind(String kind) {
this.kind = kind;
}
static class PersonBuilder {
private Stringname;
private Stringlike;
private int age;
private Stringkind;
PersonBuilder() {
}
public PersonBuilderBuilder(String name) {
this.name = name;
return this;
}
public PersonBuilderBuilder(int age) {
this.age = age;
return this;
}
PersonBuilderbuildName(String name) {
this.name = name;
return this;
}
PersonBuilderbuildAge(int age) {
this.age = age;
return this;
}
PersonBuilderbuildLike(String like) {
this.like = like;
return this;
}
PersonBuilderbuildKind(String kind) {
this.kind = kind;
return this;
}
Personbuild() {
// Person person = new ManPerson();
// person.setAge(age);
return new Person(this);
}
}
@NonNull
@Override
public StringtoString() {
return "Person:" +kind +" NAME = " +name +" LIKE =" +like +" AGE = " +age;
}
}
网友评论