Java chained programming interface and java chained Programming
When displaying an AlertDialog in android development, the following statements are often used:
new AlertDialog.Builder(getApplicationContext()) .setTitle("Dialog") .setMessage("Link program") .setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //TODO } }) .show();
It can be noted that setTitle/setMessage/setPositiveButton and Other interfaces are directly followed by execution and separated by dots. This method is called chained programming.
When you view the setTitle, setMessage, and other source code, you will find that the returned values of each method (Interface) are AlertDialog. builder type, so the secret is that the return value type of the method must be consistent with the type before the first vertex:
/** * 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; }
The advantage of this writing method is that you can determine as few types as possible, and greatly enhance the readability of the code and reduce the amount of code.
The following uses a small example to demonstrate how to create such a chained programming interface.
Public class LinkProgram {private String mText; private int mId; private boolean isAdd; public static void main (String [] args) {LinkProgram link = new LinkProgram (); // when calling a chained interface, the returned value type is consistent with the link object type. setAdd (true ). setId (5 ). setText ("hello world"); System. out. println (link) ;}@ Override public String toString () {return "Text:" + mText + ", Id:" + mId + ", add:" + isAdd ;} // The return value type is LinkProgram public LinkProgram setText (String mText) {this. mText = mText; return this;} // the return value type is LinkProgram public LinkProgram setId (int mId) {this. mId = mId; return this;} // the return value type is LinkProgram public LinkProgram setAdd (boolean isAdd) {this. isAdd = isAdd; return this ;}}
Running result:
Text: hello world, Id: 5, add: true