Sobes.tech
Middle

What is the difference between the Builder and Facade design patterns?

sobes.tech AI

Answer from AI

Builder focuses on step-by-step construction of a complex object, separating the creation process from its representation. It allows using the same construction process to create different representations of the object.

Facade provides a unified interface to a set of interfaces in a subsystem. It defines a high-level interface that makes the subsystem easier to use.

Main differences:

  • Purpose: Builder for creating objects, Facade for simplifying access to subsystems.
  • Focus: Builder on the construction process, Facade on ease of use.
  • Application: Builder is often used for objects with many optional parameters or complex initialization processes. Facade is used to hide subsystem complexity and provide a more convenient API.

Example of Builder (simplified):

// Example class with many parameters
class Car {
    private String engine;
    private String transmission;
    private int wheels;

    // Private constructor to enforce use of Builder
    private Car(Builder builder) {
        this.engine = builder.engine;
        this.transmission = builder.transmission;
        this.wheels = builder.wheels;
    }

    // Nested Builder class
    public static class Builder {
        private String engine;
        private String transmission;
        private int wheels = 4; // Default value

        public Builder setEngine(String engine) {
            this.engine = engine;
            return this;
        }

        public Builder setTransmission(String transmission) {
            this.transmission = transmission;
            return this;
        }

        public Builder setWheels(int wheels) {
            this.wheels = wheels;
            return this;
        }

        public Car build() {
            return new Car(this);
        }
    }

    // Getters (for example)
    // ...
}

// Using Builder
class Main {
    public static void main(String[] args) {
        Car myCar = new Car.Builder()
                .setEngine("V8")
                .setTransmission("Automatic")
                .build();
    }
}

Example of Facade (simplified):

// Simple subsystem
class Engine {
    public void start() {
        System.out.println("Engine starting...");
    }
}

class Gearbox {
    public void shiftUp() {
        System.out.println("Shifting up...");
    }
}

// Facade for starting the car
class CarFacade {
    private Engine engine = new Engine();
    private Gearbox gearbox = new Gearbox();

    public void startCar() {
        engine.start();
        gearbox.shiftUp();
        System.out.println("Car started.");
    }
}

// Using Facade
class Main {
    public static void main(String[] args) {
        CarFacade carFacade = new CarFacade();
        carFacade.startCar();
    }
}
What is the difference between the Builder and Facade… - sobes.tech