Java

In this example, the Builder pattern allows step by step construction of different car models.

The example also shows how Builder produces products of different kinds (car manual) using the same building steps.

The Director controls the order of the construction. It knows which building steps to call to produce this or that car model. It works with builders only via their common interface. This allows passing different types of builders to the director.

The end result is retrieved from the builder object because the director can’t know the type of resulting product. Only the Builder object knows what does it build exactly.

builders

builders/Builder.java: Common builder interface

package refactoring_guru.builder.example.builders;

import refactoring_guru.builder.example.cars.CarType;
import refactoring_guru.builder.example.components.Engine;
import refactoring_guru.builder.example.components.GPSNavigator;
import refactoring_guru.builder.example.components.Transmission;
import refactoring_guru.builder.example.components.TripComputer;

/**
 * Builder interface defines all possible ways to configure a product.
 */
public interface Builder {
    void setCarType(CarType type);
    void setSeats(int seats);
    void setEngine(Engine engine);
    void setTransmission(Transmission transmission);
    void setTripComputer(TripComputer tripComputer);
    void setGPSNavigator(GPSNavigator gpsNavigator);
}

builders/CarBuilder.java: Builder of car

builders/CarManualBuilder.java: Builder of a car manual

cars

cars/Car.java: Car product

cars/Manual.java: Manual product

cars/CarType.java

components

components/Engine.java: Product feature 1

components/GPSNavigator.java: Product feature 2

components/Transmission.java: Product feature 3

components/TripComputer.java: Product feature 4

director

director/Director.java: Director controls builders

Demo.java: Client code

OutputDemo.txt: Execution result

Last updated