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

Car builder example

In this section, we are going to apply the builder pattern to our car software. We have a Car class and we need to create instances of it. Depending on the components we add to the car, we can build sedan cars and sports cars. When we start designing our software, we realize the following:

  • The Car class is quite complex, and creating class objects is a complex operation too. Adding all of the instantiation logic in the Car constructor will make the class quite big.
  • We need to build several types of cars. Usually, for this scenario, we add several different constructors, but our intuition is telling us that this is not the best solution.
  • In the future, we probably need to build different types of car objects. The demand for semi-automatic cars is quite high already, so in the near future we should be ready to extend our code without modifying it.

We are going to create the following class structure:

CarBuilder is the builder base class and it contains four abstract methods. We created two concrete builders: ElectricCarBuilder and GasolineCarBuilder. Each of the concrete builders has to implement all of the abstract methods. The methods that are not required, such as addGasTank for the ElectricCarBuilder, are left empty or they can throw an exception. Electric and gasoline cars have different internal structures.

The Director class uses the builders to create new car objects.  buildElectricCar and buildGasolineCar may be similar, with slight differences:

public Car buildElectricCar(CarBuilder builder)
{
builder.buildCar();
builder.addEngine("Electric 150 kW");
builder.addBatteries("1500 kWh");
builder.addTransmission("Manual");
for (int i = 0; i < 4; i++)
builder.addWheel("20x12x30");
builder.paint("red");
return builder.getCar();
}

But let's assume we want to build a hybrid car with an electric and a gasoline engine:

public Car buildHybridCar(CarBuilder builder)
{
builder.buildCar();
builder.addEngine("Electric 150 kW");
builder.addBatteries("1500 kWh");
builder.addTransmission("Manual");
for (int i = 0; i < 4; i++)
builder.addWheel("20x12x30");
builder.paint("red");
builder.addGasTank("1500 kWh");
builder.addEngine("Gas 1600cc");
return builder.getCar();
}
主站蜘蛛池模板: 林甸县| 都兰县| 谷城县| 泌阳县| 巴彦淖尔市| 无为县| 剑川县| 楚雄市| 苏尼特左旗| 湘乡市| 庄河市| 繁昌县| 桃源县| 富宁县| 崇礼县| 辰溪县| 宁安市| 寻乌县| 永城市| 玉树县| 大同县| 依兰县| 木兰县| 吉林省| 四平市| 西畴县| 太康县| 栖霞市| 固镇县| 新营市| 弥勒县| 铜梁县| 石城县| 丁青县| 焦作市| 乌拉特前旗| 江孜县| 井陉县| 弥渡县| 铁岭市| 商洛市|