本文實例講述了Java及Android中常用鏈式調用寫法。分享給大家供大家參考,具體如下:
最近發現,目前大火的許多開源框架中,大多都使用了一種"(方法).(方法).(方法)"的形式進行調用,最典型的就是RxJava。android中AlertDialog控件的源碼也是這種形式的。查閱可知,大家把它叫做鏈式調用。“行動是檢驗程序的唯一標準”0.0!查了、說了那么多,還是得自己寫個例子并運行出預期的效果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
/** * * 鏈式調用 * * @author k.k * */ public class Student { public Student() { } public static Builder builder() { return new Builder(); } // 靜態內部類 static class Builder { /* 姓名 */ private String name; /* 年齡 */ private String age; /* 年級 */ private String grade; /* 學號 */ private String no; /* 專業 */ private String Professional; public String getName() { return name; } public Builder setName(String name) { this .name = name; return this ; } public String getAge() { return age; } public Builder setAge(String age) { this .age = age; return this ; } public String getGrade() { return grade; } public Builder setGrade(String grade) { this .grade = grade; return this ; } public String getNo() { return no; } public Builder setNo(String no) { this .no = no; return this ; } public String getProfessional() { return Professional; } public Builder setProfessional(String professional) { Professional = professional; return this ; } public void showMessagwe() { System.out.println( "姓名:" + this .name); System.out.println( "年齡:" + this .age); System.out.println( "班級:" + this .grade); System.out.println( "學號:" + this .no); System.out.println( "專業:" + this .Professional); } } public static void main(String[] args) { // 鏈式調用(代碼簡潔,可讀性強) Student.builder().setName( "總有刁民想害朕" ).setAge( "23" ).setGrade( "大三" ) .setNo( "20110310" ).setProfessional( "信息管理與信息系統" ).showMessagwe(); } } |
運行結果:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/myname_kk/article/details/77574472