Implementing the Facade pattern in Java means creating a single class that internally coordinates calls to several subsystem classes and exposes only a small set of high-level methods for the client to call.
Key Points: • Identify the subsystem classes whose interactions are complex or error-prone to coordinate manually. • Create a facade class that holds references to those subsystem instances. • Expose high-level methods on the facade that internally call the subsystem methods in the correct order. • Keep the subsystem classes public so advanced clients can still bypass the facade when needed. • The facade shouldn't add new business logic itself — it should just simplify coordination.
Example: A HomeTheaterFacade wraps DvdPlayer, Amplifier, and Projector objects behind a single watchMovie() method, so a client just calls homeTheater.watchMovie() instead of separately turning on the projector, dimming lights, and starting the DVD player.
Code Example:
class HomeTheaterFacade {
private final DvdPlayer dvd;
private final Amplifier amp;
private final Projector projector;
HomeTheaterFacade(DvdPlayer dvd, Amplifier amp, Projector projector) {
this.dvd = dvd;
this.amp = amp;
this.projector = projector;
}
void watchMovie() {
projector.on();
amp.on();
dvd.play();
}
}Interview Tip: A concise interview answer is:
"I implement Facade by wrapping the subsystem classes inside a new class that exposes a few high-level methods, like watchMovie() in a home theater example, which internally call the individual subsystem methods in the right order so the client doesn't need to know those details."