代碼解析
public class Test2 {
private int i = 0;
public Test2(int i) { this.i = i; }
// 關鍵:返回當前對象引用 this
public Test2 increment() {
i++;
return this;
}
public void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Test2 t = new Test2(100);
// 鏈式調用:increment() 返回 this,可繼續調用
t.increment().increment().print(); // 輸出: i = 102
}
}
核心原理
應用場景
- Builder 模式:
new StringBuilder().append("a").append("b").toString()
- 流式 API:
stream.filter().map().collect()
- 配置對象:
config.setPort(8080).setTimeout(30).build()
設計要點
- 返回類型聲明為當前類
Test2,而非 void
- 修改對象狀態後返回
this
- 不可變對象應返回新實例 (如
String, BigInteger)