Structural patterns (Adapter, Decorator, Facade) in Software Engineering - Time & Space 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?
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.
Look for repeated calls or loops that affect performance.
- Primary operation: Calling
operation()on the decorator which calls the wrapped component'soperation(). - How many times: Once per call, but can be nested if multiple decorators wrap each other.
As you add more decorators wrapping each other, each call to operation() triggers more calls inside.
| Number of Decorators (n) | Approx. Calls to operation() |
|---|---|
| 1 | 2 |
| 5 | 6 |
| 10 | 11 |
Pattern observation: The number of calls grows linearly with the number of decorators.
Time Complexity: O(n)
This means the time to complete the operation grows directly in proportion to how many decorators are added.
[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.
Understanding how structural patterns impact time helps you explain design choices clearly and shows you think about both design and performance.
What if we replaced the Decorator pattern with a Facade that calls multiple components internally? How would the time complexity change?