1 問題
建造者模式,我們也許不陌生,因為我們看到很多開源框架或者Android源碼里面用到,類似這樣的代碼結構
A a = new A.builder().method1("111").method2("222").build();
很明顯,一般這里的結構有builder()構造函數,還有build()函數,主要用來干嘛呢?還不是為了構建對象,如果需要設置的參數很多的話,一個一個去set很繁瑣也不好看,下面有個例子簡單粗暴展示。?
?
?
?
?
?
?
?
?
2 測試代碼實現
package com.example.test1;public class Student {private int id;private String name;private int age;private String classNmae;public Student(Builder builder) {this.id = builder.id;this.name = builder.name;this.age = builder.age;this.classNmae = builder.classNmae;}public int getId() {return id;}public String getName() {return name;}public int getAge() {return age;}public String getClassNmae() {return classNmae;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", age=" + age +", classNmae='" + classNmae + '\'' +'}';}public static class Builder {private int id;private String name;private int age;private String classNmae;public Builder() {}public Builder id(int id) {this.id = id;return this;}public Builder name(String name) {this.name = name;return this;}public Builder age(int age) {this.age = age;return this;}public Builder className(String classNmae) {this.classNmae = classNmae;return this;}public Student build() {return new Student(this);}}
}
Student student = new Student.Builder().name("chenyu").age(28).id(1).className("erzhong").build();Log.i(TAG, "student toString is:" + student.toString());
?
?
?
?
?
?
?
?
3 運行結果
18376-18376/com.example.test1 I/chenyu: student toString is:Student{id=1, name='chenyu', age=28, classNmae='erzhong'}
?
?
?
?
?
?
?
4 總結
1)我們需要構建一個對象很多參數的時候用這種方式
2)最關鍵的是需要構建的對象類里面有個Builder類作為參數傳遞
public Student(Builder builder) {this.id = builder.id;this.name = builder.name;this.age = builder.age;this.classNmae = builder.classNmae;}
3)最后build()函數里面返回的是需要構建的類本身
public Student build() {return new Student(this);}
?