The Facade pattern is used to simplify interactions with complex systems by providing a single, easy-to-use interface. It hides the internal details of complicated subsystems, allowing you to perform operations without worrying about the complexity behind them. An example would be a home theater system, where you can turn on multiple devices (TV, DVD player, sound system) with a single command, without having to turn each one on individually.
C# Code Example:
// Complex subsystem: TV
public class TV
{
public void TurnOn()
{
Console.WriteLine("TV turned on.");
}
public void SetChannel(int channel)
{
Console.WriteLine($"Channel set to {channel}.");
}
}
// Complex subsystem: DVD player
public class DVDPlayer
{
public void TurnOn()
{
Console.WriteLine("DVD player turned on.");
}
public void Play()
{
Console.WriteLine("Playing DVD.");
}
}
// Complex subsystem: Sound system
public class SoundSystem
{
public void TurnOn()
{
Console.WriteLine("Sound system turned on.");
}
public void SetVolume(int volume)
{
Console.WriteLine($"Volume set to {volume}.");
}
}
// Facade: Home Theater
public class HomeTheaterFacade
{
private TV _tv;
private DVDPlayer _dvdPlayer;
private SoundSystem _soundSystem;
public HomeTheaterFacade(TV tv, DVDPlayer dvdPlayer, SoundSystem soundSystem)
{
_tv = tv;
_dvdPlayer = dvdPlayer;
_soundSystem = soundSystem;
}
public void WatchMovie()
{
Console.WriteLine("Starting Home Theater...");
_tv.TurnOn();
_tv.SetChannel(3);
_dvdPlayer.TurnOn();
_dvdPlayer.Play();
_soundSystem.TurnOn();
_soundSystem.SetVolume(20);
Console.WriteLine("All set, enjoy your movie!");
}
}
class Program
{
static void Main(string[] args)
{
// Creating the subsystems
TV tv = new TV();
DVDPlayer dvdPlayer = new DVDPlayer();
SoundSystem soundSystem = new SoundSystem();
// Using the facade
HomeTheaterFacade homeTheater = new HomeTheaterFacade(tv, dvdPlayer, soundSystem);
homeTheater.WatchMovie();
}
}
Code Explanation:
Here we have three separate systems: a TV, a DVD player, and a sound system. Without the Facade pattern, you would have to turn on and configure each system individually. The HomeTheaterFacade does that job for you, turning on all the necessary systems and adjusting settings with a simple command. In the main code, calling WatchMovie automates the whole process and makes it easy to use.
Conclusion:
The Facade pattern is ideal when you want to simplify interactions with complex systems by providing an easy-to-use interface. It helps reduce coupling between parts of a system by hiding complicated details and offering a simpler way to interact with it.
Source code: GitHub