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

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();
主站蜘蛛池模板: 波密县| 苍南县| 山东省| 冀州市| 调兵山市| 岳阳县| 宜城市| 郎溪县| 揭东县| 浙江省| 康平县| 云南省| 宝丰县| 怀仁县| 武安市| 昌吉市| 桦川县| 乌兰县| 瑞金市| 玉田县| 临洮县| 安义县| 九龙县| 汶川县| 开鲁县| 赫章县| 若羌县| 灵寿县| 八宿县| 平凉市| 封丘县| 新疆| 昌邑市| 越西县| 宝鸡市| 五峰| 盖州市| 抚宁县| 明光市| 大同县| 巫山县|