This design pattern provides a simplified and unified interface to hide the inner complexities of several subsystems or libraries.
As most of the time, the user of a subsystem does not want to know about the internal complexities. He just wants a simplified interface to use the subsystem. Subsystems become complex as they evolve. A facade can provide this simplified interface to the users of the subsystem.
The main participants of the Facade design pattern are
- facade itself
- and the several subsystems
The subsystems have no knowledge about the facade - meaning they don't keep any reference to the facade.
Let me give you an example.
Suppose there are many geometrical shapes whose drawing functionalities are complex and each one must be drawn differently. But the client really does not want to go into that complexity.
Here comes the facade pattern in the rescue. This pattern will give a single method called drawShapes which will take care of all the internal complexity of the individual shapes.
Here goes the source code of the example.
from abc import ABC, abstractmethod
class Shape(ABC):
"""
Abstract base class for all shapes.
"""
@abstractmethod
def draw(self):
pass
class Circle(Shape):
"""
Concrete class for a Circle.
"""
def draw(self):
print("Special method to draw a circle")
class Rectangle(Shape):
"""
Concrete class for a Rectangle.
"""
def draw(self):
print("Special method to draw a rectangle")
class Triangle(Shape):
"""
Concrete class for a Triangle.
"""
def draw(self):
print("Special method to draw a triangle")
class FacadeToShape:
"""
The Facade provides a simplified interface to the complex subsystem of shapes.
"""
def __init__(self, circle, rectangle, triangle):
self.circle = circle
self.rectangle = rectangle
self.triangle = triangle
def draw_circle(self):
"""Draws a circle using the subsystem."""
self.circle.draw()
def draw_rectangle(self):
"""Draws a rectangle using the subsystem."""
self.rectangle.draw()
def draw_triangle(self):
"""Draws a triangle using the subsystem."""
self.triangle.draw()
def draw_shapes(self):
"""Draws all shapes in a predefined order."""
self.draw_circle()
self.draw_triangle()
self.draw_rectangle()
if __name__ == '__main__':
# The client code interacts with the Facade instead of the individual shapes.
facade_to_shape = FacadeToShape(Circle(), Rectangle(), Triangle())
facade_to_shape.draw_shapes()
Top comments (0)