JAVA中完成鏈式操作(辦法鏈)的簡略例子。本站提示廣大學習愛好者:(JAVA中完成鏈式操作(辦法鏈)的簡略例子)文章只能為提供參考,不一定能成為您想要的結果。以下是JAVA中完成鏈式操作(辦法鏈)的簡略例子正文
在應用jQuery時刻,我們常常會看到或許應用到辦法鏈,例如:
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
這段代碼的意思是選擇器選擇id為p1的html標簽,色彩變紅,以後slideup,再slidedown。
天然是可以將這幾個辦法離開寫,然則不離開的話不只有很好的易讀性,代碼量也會有削減,那末何樂而不為?
這類挪用函數的方法在jQuery中稱為“Chaining”,道理也很簡略:可以或許chaining的辦法挪用後前往對象自己便可。
上面用java代碼做個演示:
不應用chaining:
Persion.java:
public class Persion {
private int id;
private String name;
private String phoneNumber;
private String address;
public Persion() {
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setAddress(String address) {
this.address = address;
}
public void printId() {
System.out.println(this.id);
}
public void printName() {
System.out.println(this.name);
}
public void printPhoneNumber() {
System.out.println(this.phoneNumber);
}
public void printAddress() {
System.out.println(this.address);
}
}
Test.java:
public class Test {
public static void main(String[] args) {
Persion persion1 = new Persion();
persion1.setId(3);
persion1.setName("John");
persion1.setPhoneNumber("1111111");
persion1.setAddress("US");
persion1.printId();
persion1.printName();
persion1.printPhoneNumber();
persion1.printAddress();
}
}
應用chaining:
Persion.java:
public class Persion {
private int id;
private String name;
private String phoneNumber;
private String address;
public Persion() {
}
public Persion setId(int id) {
this.id = id;
return this;
}
public Persion setName(String name) {
this.name = name;
return this;
}
public Persion setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public Persion setAddress(String address) {
this.address = address;
return this;
}
public Persion printId() {
System.out.println(this.id);
return this;
}
public Persion printName() {
System.out.println(this.name);
return this;
}
public Persion printPhoneNumber() {
System.out.println(this.phoneNumber);
return this;
}
public Persion printAddress() {
System.out.println(this.address);
return this;
}
}
Test.java:
public class Test {
public static void main(String[] args) {
Persion persion1 = new Persion();
persion1.setId(3).setName("John")
.setPhoneNumber("1111111").setAddress("US");
persion1.printId()
.printName()
.printPhoneNumber()
.printAddress();
}
}
好詭異的感到~哈哈!