建造者模式(Builder): 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方法时所使用的模式。
===============================================================
Dart 默认支持Buidler模式,使用..
来表示
".." is the cascaded method invocation operation. The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.
var address = getAddress();
address.setStreet(“Elm”, “13a”);
address.city = “Carthage”;
address.state = “Eurasia”
address.zip(66666, extended: 6666);
getAddress()
..setStreet(“Elm”, “13a”)
..city = “Carthage”
..state = “Eurasia”
..zip(66666, extended: 6666);
===============================================================
Kotlin中,成员赋值方法返回Builder本身,并创建Build方法。
class Adress private constructor(builder: Builder) {
private val street: String?
private val city: String?
private val zip: String?
init {
street = builder.street
city = builder.city
zip = builder.zip
}
class Builder {
var street: String? = null
var city: String? = null
var zip: String? = null
fun street(street: String): Builder {
this.street = street
return this
}
fun city(city: String): Builder {
this.city = city
return this
}
fun zip(zip: String): Builder {
this.zip = zip
return this
}
fun build(): Adress {
return Adress(this)
}
}
}
使用:
val adress = Adress.Builder()
.street("xidajie")
.city("beijing")
.zip("6666")
.build()
===============================================================
Java中,创建静态内部类,成员赋值方法返回Builder本身,并创建Build方法。
public class Adress {
private final String street;
private String city;
private String zip;
private Adress(Builder builder) {
street = builder.street;
city = builder.city;
zip = builder.zip;
}
public static final class Builder {
private String street;
private String city;
private String zip;
public Builder() {
}
public Builder street(String street) {
this.street = street;
return this;
}
public Builder city(String city) {
this.city = city;
return this;
}
public Builder zip(String zip) {
this.zip = zip;
return this;
}
public Adress build() {
return new Adress(this);
}
}
}
===============================================================
AndroidStudio使用插件自动生成.
Plugins
中搜索 Inner Builder
,重启Android Studio,写好要构建的变量,右键Generate
Builder
生成(按 Control + Insert (Mac :command + N))。