I need to build a class which makes use of method chaining. I understand the concept of method chaining. Example:
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");
But i need to take this one step further. I need to be able to do this:
Company company = new Company()
.setCompanyName("SomeCompany")
.addPerson("Mike")
.setAddress("Street 118");
.addPerson("Jane")
.setAddress("Street 342");
.hasDriverLicense(true)
So as you can see i need to be able to continue with chaining. The method addAddress
isn't always the last method in the chain. It can be any method from the Person
class.
Is there a good way to achieve this functionality? Perhaps with method extensions or something?
Any help / examples are greatly appreciated.