優(yōu)點(diǎn):易擴(kuò)展啦鸣,使用方便靈活配置參數(shù)盈简。例如AlertDialog碑诉、Retrofit ...
缺點(diǎn):內(nèi)部變化復(fù)雜常遂,會有很多的建造類纳令。
Person person =new Person.PersonBuilder()
.buildAge(10)
.buildLike("watch TV")
.buildName("CC")
.build();
/**
* Builder 構(gòu)建模式
*/
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;
? ? }
}