Composite Pattern

Going with the name “composite” we mean compose common functionalities inside different classes so that they behave the same way wherever they are being used. We do not require to do checks to distinguish the type of instance to achieve some action. This makes classes symmetrical.

This pattern is mostly used in the problems which is structured as tree. For example, a container having contents and other containers having their contents and so on going deep down. If an operator wants to know total contents inside the container, there might be a loop that goes through the content and some condition if element is container or content and ask for its contents if element is a container.

This check can be removed if both container and contents have common functionality of listing down its contents. However, content will only give empty list as it is content itself, the problem of distinguishing is solved.

class Container:
    def __init__(self):
        self.contents = [contents]
 
    def add(self, content):
        self.contents.append(content)
        
    def get_contents(self):
        return self.contents
 
class Content:
    def get_contents(self):
        return []
 
 
container = Container()
content = Content()
container.add(content)
 
container2 = Container()
container2.add(Content())
 
container.add(container2)

In static typed language, we can either use interface or make classes inherit some base class. However in python we do not have any restriction. We can use duck typing, or interface etc to implement composite pattern.

References

  1. https://python-patterns.guide/gang-of-four/composite/