Wednesday, August 23, 2023

Facade Design Pattern in Python...

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.

The UML class diagram of the facade design pattern example looks like the following:


Here goes the source code of the example.

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def draw(self):
pass

class Circle(Shape):
def draw(self):
print("Special method to draw a circle")

class Rectangle(Shape):
def draw(self):
print("Special method to draw a rectangle")

class Triangle(Shape):
def draw(self):
print("Special method to draw a triangle")

class FacadeToShape:
def __init__(self, circle, rectangle, triangle):
self.circle = circle
self.rectangle = rectangle
self.triangle = triangle

def drawCircle(self):
self.circle.draw()
def drawRectangle(self):
self.rectangle.draw()
def drawTriangle(self):
self.triangle.draw()

def drawShapes(self):
self.drawCircle()
self.drawTriangle()
self.drawRectangle()


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
facateToShape = FacadeToShape(Circle(), Rectangle(), Triangle())
facateToShape.drawShapes()

No comments: