1. 程式人生 > >Android 構建者模式(Builder)

Android 構建者模式(Builder)

這樣吧,這次先上程式碼,再敘述

public class Student {
  private String name;
  private int age;
  private Student(Builder builder){
    this.name=builder.name;
    this.age=builder.age;
  }  
    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; } static class Builder{ private String name; private int age; public Builder name(String name){ this.name=name; return this; } public
Builder age(int age){ this.age=age; return this; } public Student build(){ return new Student(this); } } }

其實大體是這樣設計得

  • 在實體類中有一些屬性,然後在其內部靜態類Builder中也有一樣的屬性
  • 將實體類中的構造方法私有化
  • 實體類由Builder構建出來,實體類中的屬性值由構造時傳入的Builder物件為其賦值
  • Builder的每個方法都是給自己的屬性賦值,並返回自己Builder的引用

達到上面4點,則在構建時就可以這樣寫

Student.Builder builder=new Student.Builder();
Student student=builder
  .name("小明")
  .age(10)
  .build();

很爽吧…nice