Middle
238
What is the Facade pattern?
Answer from AI
sobes.tech AI
The Facade pattern is a structural design pattern that provides a simple interface to a complex subsystem of classes, frameworks, or a set of functions.
Main goals:
- Simplify the use of a complex system.
- Reduce coupling between the client and the subsystem.
- Make the code more readable and maintainable.
Working principle:
The facade hides the complexity of the subsystem by redirecting client calls to the appropriate objects within the subsystem. The client interacts only with the facade, without knowing the details of the internal components' implementation.
Example:
# Subsystem: classes representing components of a complex system
class Amplifier:
def on(self):
print("Amplifier on")
def off(self):
print("Amplifier off")
def set_volume(self, level):
print(f"Amplifier volume set to {level}")
def set_source(self, source):
print(f"Amplifier source set to {source}")
class Tuner:
def on(self):
print("Tuner on")
def off(self):
print("Tuner off")
def set_am(self):
print("Tuner set to AM")
def set_fm(self):
print("Tuner set to FM")
def set_frequency(self, frequency):
print(f"Tuner frequency set to {frequency}")
class DvdPlayer:
def on(self):
print("DVD Player on")
def off(self):
print("DVD Player off")
def play(self, movie):
print(f"Playing movie: {movie}")
# Facade pattern: provides a simple interface to the subsystem
class HomeTheaterFacade:
def __init__(self, amp, tuner, dvd):
self.amp = amp
self.tuner = tuner
self.dvd = dvd
def watch_movie(self, movie):
print("Get ready to watch a movie...")
self.dvd.on()
self.amp.on()
self.amp.set_source("DVD")
self.amp.set_volume(5)
self.dvd.play(movie)
def end_movie(self):
print("Shutting down the home theater...")
self.dvd.off()
self.amp.off()
# Client usage of the facade
if __name__ == "__main__":
amplifier = Amplifier()
tuner = Tuner()
dvd_player = DvdPlayer()
home_theater = HomeTheaterFacade(amplifier, tuner, dvd_player)
home_theater.watch_movie("Raiders of the Lost Ark")
print("-" * 20)
home_theater.end_movie()
Advantages:
- Simplification: Hides the complexity of the subsystem.
- Reduced coupling: The client does not depend directly on many classes of the subsystem.
- Improved readability: Client code becomes more understandable.
- Easier maintenance: Changes within the subsystem are less likely to affect client code.
Disadvantages:
- Potential bloat: If the facade becomes too large, it can itself become "thick" and hard to manage.
- Limited flexibility: The facade provides a predefined set of operations. Direct access to the subsystem may be needed for more flexible scenarios.
Applicability:
Used when it is necessary to provide a simple and unified way to interact with a complex system consisting of many interconnected objects.