The Facade design pattern provides a simplified interface to a complex subsystem. It creates a single class that acts as a facade, hiding the complexities of the underlying components and providing a unified, easy-to-use interface to the client.
Here is a Java example demonstrating the Facade pattern with a home theater system: // Subsystem Components
class DVDPlayer {
public void on() {
System.out.println("DVD Player On");
}
public void play(String movie) {
System.out.println("Playing movie: " + movie);
}
public void off() {
System.out.println("DVD Player Off");
}
}
class Projector {
public void on() {
System.out.println("Projector On");
}
public void wideScreenMode() {
System.out.println("Projector in widescreen mode");
}
public void off() {
System.out.println("Projector Off");
}
}
class SoundSystem {
public void on() {
System.out.println("Sound System On");
}
public void setVolume(int level) {
System.out.println("Sound System volume set to " + level);
}
public void off() {
System.out.println("Sound System Off");
}
}
// Facade Class
class HomeTheaterFacade {
private DVDPlayer dvdPlayer;
private Projector projector;
private SoundSystem soundSystem;
public HomeTheaterFacade(DVDPlayer dvdPlayer, Projector projector, SoundSystem soundSystem) {
this.dvdPlayer = dvdPlayer;
this.projector = projector;
this.soundSystem = soundSystem;
}
public void watchMovie(String movie) {
System.out.println("Get ready to watch a movie...");
projector.on();
projector.wideScreenMode();
soundSystem.on();
soundSystem.setVolume(10);
dvdPlayer.on();
dvdPlayer.play(movie);
}
public void endMovie() {
System.out.println("Shutting down home theater...");
dvdPlayer.off();
soundSystem.off();
projector.off();
}
}
// Client Code
public class FacadePatternDemo {
public static void main(String[] args) {
DVDPlayer dvdPlayer = new DVDPlayer();
Projector projector = new Projector();
SoundSystem soundSystem = new SoundSystem();
HomeTheaterFacade homeTheater = new HomeTheaterFacade(dvdPlayer, projector, soundSystem);
homeTheater.watchMovie("The Matrix");
System.out.println("\n");
homeTheater.endMovie();
}
}
Subsystem Components:
DVDPlayer
, Projector
, and SoundSystem
represent the complex parts of the home theater system, each with its own specific methods.
Facade Class:
HomeTheaterFacade
acts as the facade. It encapsulates the interactions with the subsystem components. Methods like watchMovie()
and endMovie()
provide a simplified interface to the client, handling the orchestration of multiple component actions internally.
Client Code:
The FacadePatternDemo
class demonstrates how a client interacts only with the HomeTheaterFacade
to perform complex operations like watching or ending a movie, without needing to know the intricate details of each individual component.
No comments:
Post a Comment