- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 158字
- 2021-06-25 20:52:34
Anonymous builders with method chaining
As described previously, the most intuitive way to deal with objects from the same class that should take different forms is to create several constructors to instantiate them for each scenario. Using builder patterns to avoid this is a good practice. In Effective Java, Joshua Bloch proposes using inner builder classes and method chaining to replace multiple constructors.
Method chaining is a technique to return the current object (this) from certain methods. This way, the methods can be invoked in a chain. For example:
public Builder setColor()
{
// set color
return this;
}
After we have defined more methods like this, we can invoke them in a chain:
builder.setColor("Blue")
.setEngine("1500cc")
.addTank("50")
.addTransmission("auto")
.build();
But, in our case, we are going to make builder an inner class of the Car object. So, when we need a new client, we can do the following:
Car car = new Car.Builder.setColor("Blue")
.setEngine("1500cc")
.addTank("50")
.addTransmission("auto")
.build();