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();
}
}
好诡异的感觉~哈哈!
下一篇: Java进阶教程之String类