在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