0
0
Software Engineeringknowledge~5 mins

Behavioral patterns (Observer, Strategy, Command) in Software Engineering - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Behavioral patterns (Observer, Strategy, Command)
O(n)
Understanding Time Complexity

Behavioral design patterns help organize how objects interact and change behavior. Analyzing their time complexity shows how the cost of these interactions grows as the number of objects or commands increases.

We want to understand how the execution time changes when using Observer, Strategy, or Command patterns as the system grows.

Scenario Under Consideration

Analyze the time complexity of notifying observers in the Observer pattern.


class Subject:
    def __init__(self):
        self.observers = []

    def register(self, observer):
        self.observers.append(observer)

    def notify(self, message):
        for observer in self.observers:
            observer.update(message)

This code shows a subject notifying all registered observers by calling their update method.

Identify Repeating Operations

Look at what repeats when notify is called.

  • Primary operation: Looping through all observers to call update.
  • How many times: Once for each observer registered.
How Execution Grows With Input

As the number of observers grows, the notify method calls update more times.

Input Size (n)Approx. Operations
1010 update calls
100100 update calls
10001000 update calls

Pattern observation: The number of operations grows directly with the number of observers.

Final Time Complexity

Time Complexity: O(n)

This means the time to notify observers grows linearly with how many observers there are.

Common Mistake

[X] Wrong: "Notifying observers happens instantly no matter how many there are."

[OK] Correct: Each observer must be updated one by one, so more observers mean more work and more time.

Interview Connect

Understanding how behavioral patterns affect time helps you explain design choices clearly. It shows you can think about both design and performance, a valuable skill in real projects.

Self-Check

What if the notify method used multiple threads to update observers in parallel? How would the time complexity change?