1寇甸、模式定義
- 造者模式:將一個(gè)復(fù)雜對(duì)象的構(gòu)建與它的表示分離,使得同樣的構(gòu)建過(guò)程可以創(chuàng)建不同的表示价涝。建造者模式是一步一步創(chuàng)建一個(gè)復(fù)雜的對(duì)象亡资,它允許用戶只通過(guò)指定復(fù)雜對(duì)象的類型和內(nèi)容就可以構(gòu)建它們,用戶不需要知道內(nèi)部的具體構(gòu)建細(xì)節(jié)怜跑。建造者模式屬于對(duì)象創(chuàng)建型模式样勃。根據(jù)中文翻譯的不同,建造者模式又可以稱為生成器模式性芬。
- ==使用場(chǎng)景:在構(gòu)建對(duì)象的過(guò)程可能要配置很多很多的參數(shù)峡眶,可以使用建造者模式。==
2植锉、代碼實(shí)現(xiàn)
public class Person {
private String name;
private int age;
private double height;
private double weight;
private Person(Builder builder) {
this.name=builder.name;
this.age=builder.age;
this.height=builder.height;
this.weight=builder.weight;
}
public static class Builder{
private String name;
private int age;
private double height;
private double weight;
public Builder name(String name){
this.name=name;
return this;
}
public Builder age(int age){
this.age=age;
return this;
}
public Builder height(double height){
this.height=height;
return this;
}
public Builder weight(double weight){
this.weight=weight;
return this;
}
public Person build(){
return new Person(this);
}
}
}
public class TestDemo {
public static void main(String[] args) {
Person.Builder builder=new Person.Builder();
Person person=builder.name("張三")
.age(18)
.height(178.5)
.weight(67.4)
.build();
}
}
3辫樱、Android中Builder模式常見(jiàn)實(shí)例
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者