我需要构建一个使用方法链接的类。我理解方法链的概念。例子:
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
类中的任何方法。
有没有实现此功能的好方法?也许有方法扩展之类的?
非常感谢任何帮助/示例。