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

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();
主站蜘蛛池模板: 宝山区| 祁阳县| 噶尔县| 湖州市| 黔江区| 昭通市| 江口县| 于田县| 隆德县| 会东县| 松江区| 临城县| 社会| 通渭县| 张掖市| 琼中| 家居| 东兰县| 温州市| 绥阳县| 抚顺县| 噶尔县| 永康市| 浪卡子县| 句容市| 宁安市| 包头市| 永善县| 卢湾区| 丹棱县| 荥阳市| 玉树县| 岢岚县| 西平县| 南京市| 监利县| 康马县| 托克托县| 龙南县| 安龙县| 巴林左旗|