class PersonMethodChaining {
private String name;
private int age;
// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.
public PersonMethodChaining setName(String name) {
this.name = name;
return this;
}
public PersonMethodChaining setAge(int age) {
this.age = age;
return this;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
PersonMethodChaining person = new PersonMethodChaining();
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter").setAge(21).introduce();
}
}
无方法链接
class Person {
private String name;
private int age;
// Per normal Java style, the setters return void.
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
Person person = new Person();
// Not using chaining; longer than the chained version above.
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter");
person.setAge(21);
person.introduce();
}
}
方法链接(也称为命名参数 idiom)是在面向对象的编程语言中调用多个方法调用的常用语法。每个方法返回一个对象,允许在单个语句中将调用链接在一起。链是句法糖,它消除了对中间变量的需求。方法链也被称为火车残骸,因为即使方法之间经常添加换行符,也随着更多方法链接在一起,在同一行中一个接一个地出现的方法数量增加。
类似的语法是方法级联,其中在方法调用后,表达式的计算结果为当前对象,而不是方法的返回值。级联可以使用方法链接实现,方法是让方法返回当前对象本身(this)。级联是流畅接口中的一项关键技术,并且由于链接在面向对象的语言中广泛实现,而级联则不是,因此这种形式的“通过返回此进行级联链接”通常简称为“链接”。链接和级联都来自Smalltalk语言。