最近看Rxjava觉得那个链式调用好神奇啊,一路上.....就可以各种赋值了。嗯,突然想到Java里面的StringBuffer也是这样的,大致研究了下发现就是不停返回当前类对象对象就行了。嗯,这个很强势。我在这记录下这东西怎么玩。talk is cheap,show me code.
首先是一个狗的类(这里的set方法全部返回当前this对象)
public class Dog {
private int age;
private String color;
private String voice;
public int getAge() {
return age;
}
public Dog setAge(int age) {
this.age = age;
return this;
}
public String getColor() {
return color;
}
public Dog setColor(String color) {
this.color = color;
return this;
}
public String getVoice() {
return voice;
}
public Dog setVoice(String voice) {
this.voice = voice;
return this;
}
@Override
public String toString() {
return "Dog [age=" + age + ", color=" + color + ", voice=" + voice + "]";
};
}
然后就是调用了,这个很easy
public static void main(String[] args) {
Dog dog = new Dog()
.setAge(10)
.setColor("BLACK")
.setVoice("high");
System.out.println(dog.toString());
}
这个东西可能没多 技术高,但是感觉好神奇。-_-||