What is the Builder pattern, and how is it different from the Factory pattern?
The Builder pattern is a creational design pattern that provides a way to construct a complex object step by step. It separates the construction of an object from its representation, allowing the same construction process to create different representations.
- Key points:
- Step-by-step construction: The pattern allows constructing an object by specifying each step of the creation process.
- Complex objects: It is ideal for creating objects with many optional components or configurations.
- Fluent interface: Often implemented with method chaining, making the construction process easy to follow.
-
Example:
public class Car { private String engine; private String color; private int wheels; private Car(CarBuilder builder) { this.engine = builder.engine; this.color = builder.color; this.wheels = builder.wheels; } public static class CarBuilder { private String engine; private String color; private int wheels; public CarBuilder setEngine(String engine) { this.engine = engine; return this; } public CarBuilder setColor(String color) { this.color = color; return this; } public CarBuilder setWheels(int wheels) { this.wheels = wheels; return this; } public Car build() { return new Car(this); } } }
Usage:
Car car = new Car.CarBuilder() .setEngine("V8") .setColor("Red") .setWheels(4) .build();
- Difference from Factory Pattern:
- Factory creates an object in one step, typically based on input parameters, and is ideal for simpler object creation.
- Builder is used when the object is complex and requires a series of steps to construct, often with optional attributes, allowing more flexibility in object creation.
In summary, the Builder pattern is used for constructing complex objects step by step, while the Factory pattern is used for creating simple objects in one step.