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

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();
主站蜘蛛池模板: 灵川县| 依安县| 温宿县| 凤山县| 新巴尔虎左旗| 阳曲县| 寿光市| 若尔盖县| 香格里拉县| 通辽市| 卓尼县| 枣强县| 扎兰屯市| 垣曲县| 陕西省| 望城县| 高平市| 略阳县| 博白县| 手机| 浙江省| 土默特左旗| 九龙城区| 奉新县| 惠安县| 柯坪县| 宁海县| 合川市| 博客| 清苑县| 元氏县| 贵定县| 高唐县| 杭州市| 平罗县| 大厂| 乌鲁木齐县| 泰顺县| 荔波县| 旬阳县| 闵行区|