链式调用采用的是Object.method().method().method().method()····的形式,比如
StringBuffer stringBuffer =new StringBuffer();
stringBuffer.append("1").append("2").append("3").append("4").append("5");
这样做的好处很明显,省略了很多代码。
查看下append方法
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
}
关键是第二行,return this;将 StringBuffer 对象返回,改造方法这时在写set方法的时候返回类型为其本身
public void setAge(int age) {
this.age = age;
}
改为
public Person setAge(int age) {
this.age = age;
return this;
}
我们在使用的时候则可以使用
Person person=new Person();
person.setAge(18).setName("vadon");
本文介绍了链式调用的概念及其实现方式,并通过具体的代码示例展示了如何在Java中实现链式调用,同时对比了传统方法与链式调用的区别。
648

被折叠的 条评论
为什么被折叠?



