Friday, August 18, 2023

Composite Design Pattern in Python....

 When I first started studying the Gang of Four book back in 2003-2004, it was an absolutely new thing to me. I must admit today that not everything became clear at that time. But gradually, the knowledge is being imbibed, and now while teaching my young son Ridit on this subject, I just love it.

Moreover, as I am now comfortable with three languages namely C++, Java, and Python, recreating the stuff for various languages looks pretty easy now.

So, today, I am rewriting the Composite Design Pattern in Python. Here goes my original Composite Design pattern implemented using C++ and written in 2008.





And here goes the exploration of the Composite Design Pattern by my young son, Ridit, currently a class VII student.



And here goes the Composite Design Pattern implemented in Python.

I hope you will like it.

from abc import ABC, abstractmethod

class Shape(ABC):

def __init__(self):
self.parent = None
@abstractmethod
def add(self, shape):
pass

@abstractmethod
def remove(self, shape):
pass

def getparent(self):
return self.parent

def setparent(self, parent):
self.parent = parent

@abstractmethod
def display(self):
pass


class CompositeShape(Shape):
def __init__(self):
self.listofShapes = []

def add(self, shape):
shape.setparent(self)
self.listofShapes.append(shape)


def remove(self, shape):
self.listofShapes.remove(shape)
shape.setparent(None)

def setParent(self, parent):
self.parent = parent

def display(self):
pass


class Point(Shape):
def __init__(self, x, y):
self.x = x
self.y = y

def display(self):
print ("X = ", self.x, "Y = ", self.y)

def add(self, shape):
print("This is a leaf class.... Can't add to it...")

def remove(self, shape):
print("This is a leaf class.... Can't remove from it...")

class Line(CompositeShape):
def __init__(self, p1, p2):
super().__init__()
self.add(p1)
self.add(p2)

def display(self):
print("The starting and end points of the line are")
for shape in self.listofShapes:
shape.display()

class Quadrilateral(CompositeShape):
def __init__(self, p1,p2,p3,p4):
super().__init__()
self.add(p1)
self.add(p2)
self.add(p3)
self.add(p4)

def display(self):
print("The four corners of the quadrilateral are ")
for shape in self.listofShapes:
shape.display()


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
p1 = Point(10,20)
p2 = Point(30,40)
p3 = Point(50,60)
p4 = Point(70,80)

p1.add(p2)

L1 = Line(p1,p2)
q1 = Quadrilateral(p1,p2,p3,p4)

p1.display()
p2.display()
L1.display()

q1.display()

If we execute the above code, the console window will display the following result


This is a leaf class... Can't add to it...
X =  10 Y =  20
X =  30 Y =  40
The starting and end points of the line are
X =  10 Y =  20
X =  30 Y =  40
The four corners of the quadrilateral are 
X =  10 Y =  20
X =  30 Y =  40
X =  50 Y =  60
X =  70 Y =  80

No comments: