方法链


#乱炖


2013-09-15

在使用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();
    }
}


( 本文完 )