Middle
What is the difference between the Builder design pattern and the Facade design pattern?
sobes.tech AI
Answer from AI
The Builder pattern is designed for step-by-step creation of a complex object with flexible parameter configuration. It separates the process of constructing an object from its representation, allowing different variants of the object to be created with the same construction process.
Example of using Builder:
public class Car {
private String engine;
private int wheels;
private String color;
private Car(Builder builder) {
this.engine = builder.engine;
this.wheels = builder.wheels;
this.color = builder.color;
}
public static class Builder {
private String engine;
private int wheels;
private String color;
public Builder setEngine(String engine) {
this.engine = engine;
return this;
}
public Builder setWheels(int wheels) {
this.wheels = wheels;
return this;
}
public Builder setColor(String color) {
this.color = color;
return this;
}
public Car build() {
return new Car(this);
}
}
}
The Facade pattern provides a simplified interface to a complex system of classes, libraries, or frameworks. It hides the complexity of the subsystem and makes it easier to interact with.
Example of Facade:
public class ComputerFacade {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public ComputerFacade() {
cpu = new CPU();
memory = new Memory();
hardDrive = new HardDrive();
}
public void start() {
cpu.freeze();
memory.load(0, hardDrive.read(0, 1024));
cpu.execute();
}
}
Key differences:
- Builder focuses on creating an object step by step.
- Facade simplifies interaction with an existing complex system.
Thus, Builder helps in creating objects, while Facade simplifies the use of subsystems.