Middle
What is a facade in the context of programming and how is it used?
sobes.tech AI
Answer from AI
Design pattern that provides a unified interface to a set of interfaces in a subsystem. It defines a high-level interface that makes the subsystem easier to use.
Usage:
- Simplifies complex systems by providing a single entry point.
- Reduces coupling between the client and the subsystem, allowing internal structures to change without affecting clients.
- Provides a limited set of operations for the client, hiding implementation details.
Example:
# Subsystem
class Amplifier:
def on(self):
print("Amplifier on")
def off(self):
print("Amplifier off")
def set_volume(self, volume):
print(f"Amplifier volume set to {volume}")
class Tuner:
def on(self):
print("Tuner on")
def off(self):
print("Tuner off")
def set_frequency(self, frequency):
print(f"Tuner frequency set to {frequency}")
# Facade
class HomeTheaterFacade:
def __init__(self, amp, tuner):
self._amplifier = amp
self._tuner = tuner
def watch_movie(self, movie):
print("Get ready to watch a movie...")
self._amplifier.on()
self._amplifier.set_volume(5)
self._tuner.off() # Assume tuner is not needed for the movie
def end_movie(self):
print("Shutting down home theater...")
self._amplifier.off()
self._tuner.off()
# Client code
# amp = Amplifier()
# tuner = Tuner()
# home_theater = HomeTheaterFacade(amp, tuner)
# home_theater.watch_movie("Inception")
# home_theater.end_movie()