我需要构建一个类,它可以使用方法链。我理解方法链的概念。例如:
class Company
{
private String companyName;
public setCompanyName(String companyName)
{
this.companyName = companyName;
return this;
}
public Person addPerson(String name)
{
person = new Person();
person.setName(name);
return person;
}
}
class Person
{
private String name;
private String address;
private bool license
public Person setName(String name)
{
this.name = name;
return this;
}
public Person hasDriverLicense(bool license)
{
this.license = license;
return this;
}
public Person setAddress(String address)
{
this.address = address;
return this;
}
}
//in some other class / method i do:
Company company = new Company()
.setCompanyName("SomeCompany")
.addPerson("Mike")
.setAddress("Street 118");
但我需要更进一步。我需要能够做到这一点:
Company company = new Company()
.setCompanyName("SomeCompany")
.addPerson("Mike")
.setAddress("Street 118");
.addPerson("Jane")
.setAddress("Street 342");
.hasDriverLicense(true)
所以,正如您所看到的,我需要能够继续链接。方法
addAddress
并不总是在链中的最后一个方法。它可以是Person
类中的任何方法。有没有好的方法来实现这个功能?也许可以使用方法扩展或其他什么东西?
非常感谢任何帮助/示例。
var company = ...; company.addPerson(...).setAddress(...); company.addPerson(...).setAddress(...);
- Marc Gravellvar company = new Company { Name = "SomeCompany", People = { new Person {Name = Mike", Address = "Street 118"}, new Person {Name="Jane", Address = "Street 342", HasDriverLicence = true}}};
(在IDE中看起来比压缩成一个注释要漂亮!) - Marc Gravell