官术网_书友最值得收藏!

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();
主站蜘蛛池模板: 乐都县| 阳泉市| 张掖市| 秦安县| 山西省| 卓资县| 织金县| 鹤山市| 庆阳市| 米泉市| 东平县| 浦江县| 迁安市| 合阳县| 策勒县| 托克逊县| 古交市| 旌德县| 华阴市| 平利县| 舟山市| 资阳市| 温宿县| 康保县| 万宁市| 岚皋县| 英吉沙县| 泰顺县| 钟祥市| 贡觉县| 东光县| 吴旗县| 仁寿县| 尉氏县| 紫阳县| 汶上县| 买车| 福贡县| 易门县| 漠河县| 师宗县|