Facade Pattern
1. Introduction
The Facade Pattern is a structural design pattern that provides a simplified interface to a complex system of classes, libraries, or frameworks. It acts as a front-facing interface masking more complex underlying or structural code.
This pattern is particularly useful in managing and simplifying interactions with complex subsystems.
2. Key Concepts
- Provides a unified interface to a set of interfaces in a subsystem.
- Decouples a client from the complex subsystem.
- Simplifies usage of complex systems, promoting easier integration.
Note: The Facade Pattern does not prevent the client from using the subsystem classes directly. It simply provides a simpler way to interact with them.
3. Implementation
Below is a simple implementation of the Facade Pattern in a home theater system:
class Amplifier {
public void on() { System.out.println("Amplifier is on"); }
public void off() { System.out.println("Amplifier is off"); }
}
class DVDPlayer {
public void on() { System.out.println("DVD Player is on"); }
public void play(String movie) { System.out.println("Playing " + movie); }
}
class Projector {
public void on() { System.out.println("Projector is on"); }
public void off() { System.out.println("Projector is off"); }
}
class HomeTheaterFacade {
private Amplifier amplifier;
private DVDPlayer dvdPlayer;
private Projector projector;
public HomeTheaterFacade(Amplifier amp, DVDPlayer dvd, Projector proj) {
this.amplifier = amp;
this.dvdPlayer = dvd;
this.projector = proj;
}
public void watchMovie(String movie) {
projector.on();
amplifier.on();
dvdPlayer.on();
dvdPlayer.play(movie);
}
public void endMovie() {
dvdPlayer.off();
amplifier.off();
projector.off();
}
}
// Client code
public class HomeTheaterTestDrive {
public static void main(String[] args) {
Amplifier amp = new Amplifier();
DVDPlayer dvd = new DVDPlayer();
Projector proj = new Projector();
HomeTheaterFacade homeTheater = new HomeTheaterFacade(amp, dvd, proj);
homeTheater.watchMovie("Inception");
homeTheater.endMovie();
}
4. Best Practices
- Use Facade when you want to provide a simple interface to a complex subsystem.
- Consider the Facade as a single point of access to a system's functionality.
- Keep the Facade interface minimal, exposing only the necessary functionality.
5. FAQ
What is the main benefit of using the Facade Pattern?
The main benefit is simplicity; it reduces the complexity of interactions with the subsystem by providing a single unified interface.
Can the Facade Pattern prevent direct access to subsystem classes?
No, it does not prevent access; it simply provides a simplified way to use them.