0
0
Software Engineeringknowledge~5 mins

Structural patterns (Adapter, Decorator, Facade) in Software Engineering - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Structural patterns (Adapter, Decorator, Facade)
O(n)
Understanding Time Complexity

We want to understand how the time it takes to use structural patterns changes as the size of the input or system grows.

Specifically, how do Adapter, Decorator, and Facade patterns affect the speed of a program?

Scenario Under Consideration

Analyze the time complexity of the following example using the Decorator pattern.


class Component:
    def operation(self):
        return "Base"

class Decorator(Component):
    def __init__(self, component):
        self.component = component
    def operation(self):
        return f"Decorated({self.component.operation()})"

component = Component()
decorated = Decorator(component)
result = decorated.operation()

This code wraps a base component with a decorator that adds extra behavior when calling operation.

Identify Repeating Operations

Look for repeated calls or loops that affect performance.

  • Primary operation: Calling operation() on the decorator which calls the wrapped component's operation().
  • How many times: Once per call, but can be nested if multiple decorators wrap each other.
How Execution Grows With Input

As you add more decorators wrapping each other, each call to operation() triggers more calls inside.

Number of Decorators (n)Approx. Calls to operation()
12
56
1011

Pattern observation: The number of calls grows linearly with the number of decorators.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the operation grows directly in proportion to how many decorators are added.

Common Mistake

[X] Wrong: "Using these patterns does not affect performance at all."

[OK] Correct: Each added layer (like a decorator or adapter) adds extra method calls, which can increase execution time especially if many layers are stacked.

Interview Connect

Understanding how structural patterns impact time helps you explain design choices clearly and shows you think about both design and performance.

Self-Check

What if we replaced the Decorator pattern with a Facade that calls multiple components internally? How would the time complexity change?