What does "director" mean in the Builder pattern?
Director in the Builder pattern is an object that controls the order and logic of assembling a complex product, using a builder, but does not know the implementation details of that builder.
1. The essence of the role
Director is responsible for deciding which steps and in what order must be called to assemble the product. It does not create the object itself, it coordinates the assembly process, passing instructions to the builder.
2. Why it is needed
- To encapsulate the assembly algorithm: the client does not need to know exactly how the object is created.
- To make it possible to use the same builder with different assembly scenarios (different "recipes" for the object).
- To separate responsibilities: the builder handles the details, the director handles the sequence.
3. Example (Java)
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void constructSportsCar() {
builder.reset();
builder.setSeats(2);
builder.setEngine("V8");
builder.setTripComputer(true);
builder.setGPS(true);
}
}Here Director controls the process of assembling a sports car but does not know which exact object is being created: a Car or a CarManual.
4. Advantages of using it
- Easy to change the assembly sequence (you can create new scenarios without changing the builder).
- You can use one builder for different product types.
- Simplifies testing and reusing assembly algorithms.
5. Conclusion
Director is the "manager of the assembly process", defining the "recipe" for creating the object rather than its implementation. It makes the construction process controllable, reproducible, and independent of specific classes.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.