在android開發中顯示一個AlertDialog時,常采用下列的寫法:
new AlertDialog.Builder(getApplicationContext()) .setTitle("Dialog") .setMessage("Link program") .setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //TODO } }) .show();
可以注意到setTitle/setMessage/setPositiveButton等接口都是直接緊接着執行,用點號隔開,這樣的方法叫做鏈式編程。
觀看setTitle,setMessage等源碼會發現,每個方法(接口)的返回值都是AlertDialog.Builder類型,所以秘訣在於方法的返回值類型都必須與第一個點號前面的類型保持一致:
/** * Set the title displayed in the {@link Dialog}. * * @return This Builder object to allow for chaining of calls to set methods */ public Builder setTitle(CharSequence title) { P.mTitle = title; return this; } /** * Set the message to display. * * @return This Builder object to allow for chaining of calls to set methods */ public Builder setMessage(CharSequence message) { P.mMessage = message; return this; }
這樣寫法的好處在於一方面可以盡可能少去進行類型轉換的判定,而且大大增強了代碼的閱讀性,同時也減少了代碼量。
下面通過一個小例子來演示如何制作這樣的鏈式編程接口
public class LinkProgram { private String mText; private int mId; private boolean isAdd; public static void main(String[] args) { LinkProgram link = new LinkProgram(); //鏈式接口調用時,返回值類型和link該對象類型保持一致 link.setAdd(true) .setId(5) .setText("hello world"); System.out.println(link); } @Override public String toString() { return "Text:" + mText + ", Id:" + mId + ", add:" + isAdd; } //返回值類型為LinkProgram public LinkProgram setText(String mText) { this.mText = mText; return this; } //返回值類型為LinkProgram public LinkProgram setId(int mId) { this.mId = mId; return this; } //返回值類型為LinkProgram public LinkProgram setAdd(boolean isAdd) { this.isAdd = isAdd; return this; } }
運行結果:
Text:hello world, Id:5, add:true