Informações

Prazo de entrega 11/05/2026 18:15:00
Limite de submissão No limitation

Entrar

Bonus: The Composite Pattern

Nested sub-patterns

To be as close as possible to the compound file system that you saw last time, the sub-pattern system of Pyttern allows nested sub-patterns. This enables the definition of complex logic between sub-patterns. In this exercise, you will have to define multiple sub-patterns to match the Composite pattern.

This is a bonus exercise if you have time at the end of the session. It can help you for the assignment on Program Query Language.

Scenario

The Composite pattern allows you to treat individual objects and compositions of objects uniformly. This is a complex pattern involving inheritance and recursion. You can find all the details about the Composite pattern on the refactoring.guru website.

Task

Build the composite.myt sub-pattern. This pattern is composed of two main sub-patterns: Composite and CompositeBody.

Structure to match:

  1. A base ?Component class with an ?execute method.
  2. A ?Leaf class that inherits from ?Component.
  3. A ?Composite class that:
    • Inherits from ?Component.
    • Has an __init__ initializing a list of ?children.
    • Has add and remove methods for ?children.
    • Has an ?execute method that loops through ?children and calls their ?execute method.

Example:

class Component:

    def parent(self):
        return self._parent

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

    def add(self, component):
        pass

    def remove(self, component):
        pass

    def is_composite(self):
        return False

    def operation(self):
        pass


class Leaf(Component):

    def operation(self):
        return "Leaf"


class Composite(Component):
    def __init__(self):
        self._children = []

    def add(self, component):
        self._children.append(component)
        component.parent = self

    def remove(self, component):
        self._children.remove(component)
        component.parent = None

    def is_composite(self):
        return True

    def operation(self):
        results = []
        for child in self._children:
            results.append(child.operation())
        return f"Branch({'+'.join(results)})"

Questão 1: Pyttern
Questão 2: Sub-Pattern