Bird
Raised Fist0
Software Engineeringknowledge~10 mins

Behavioral patterns (Observer, Strategy, Command) in Software Engineering - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Behavioral patterns (Observer, Strategy, Command)
Start
↓
Choose Pattern
↓
Observer
↓
Subject
↓
Notify Observers
↓
Observers Update
↓
End
This flow shows how you start by choosing one of the three behavioral patterns, then follow its steps: Observer notifies observers, Strategy selects and runs an algorithm, Command executes a command.
Execution Sample
Software Engineering
1. Observer: Subject notifies observers on change
2. Strategy: Context uses chosen algorithm
3. Command: Invoker executes command object
This example shows the main action each pattern performs during execution.
Analysis Table
StepPatternActionResult
1ObserverSubject state changesPrepare to notify observers
2ObserverSubject calls notify()Observers receive update call
3ObserverObservers update()Observers react to change
4StrategyContext selects strategyStrategy algorithm set
5StrategyContext calls strategy.execute()Algorithm runs with data
6StrategyAlgorithm returns resultContext uses result
7CommandInvoker receives command objectCommand ready to execute
8CommandInvoker calls command.execute()Command performs action
9CommandCommand completesInvoker continues workflow
10AllPatterns complete their actionsSystem behavior updated
💡 All patterns finish their respective actions and update system state accordingly
State Tracker
VariableStartAfter Step 2After Step 5After Step 8Final
Subject StateInitialChangedChangedChangedChanged
Observers NotifiedNoYesYesYesYes
Strategy AlgorithmNoneNoneSetSetSet
Strategy ResultNoneNoneComputedComputedComputed
Command ObjectNoneNoneNoneExecutingExecuted
Invoker StateIdleIdleIdleExecutingIdle
Key Insights - 3 Insights
Why does the Observer pattern notify all observers instead of just one?
Because the execution_table rows 2 and 3 show the Subject calls notify(), which triggers update() on all observers to keep them all synchronized.
How does the Strategy pattern allow changing behavior at runtime?
As seen in execution_table row 4, the Context selects a strategy algorithm dynamically, allowing different algorithms to run without changing Context code.
What is the role of the Command object in the Command pattern?
From execution_table rows 7 and 8, the Command object encapsulates an action and its parameters, letting the Invoker execute it later, decoupling request from execution.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step do observers receive the update call?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Check the 'Action' and 'Result' columns for Observer pattern steps in execution_table rows 2 and 3.
According to variable_tracker, when is the Strategy algorithm set?
AAfter Step 2
BAfter Step 5
CAfter Step 4
DAfter Step 8
💡 Hint
Look at the 'Strategy Algorithm' row and see when it changes from None to Set.
If the Command object was never created, which step in execution_table would be missing?
AStep 3
BStep 5
CStep 7
DStep 9
💡 Hint
Refer to the 'Command' pattern steps in execution_table, especially where the Command object is prepared.
Concept Snapshot
Behavioral patterns help objects communicate and change behavior.
Observer: Subject notifies many observers on change.
Strategy: Context selects algorithm at runtime.
Command: Encapsulates requests as objects for flexible execution.
They improve flexibility and decouple components.
Full Transcript
Behavioral patterns include Observer, Strategy, and Command. Observer lets a subject notify multiple observers when its state changes. Strategy allows selecting different algorithms at runtime without changing the context. Command encapsulates a request as an object, letting invokers execute commands flexibly. The execution flow starts by choosing a pattern, then performing its main actions: notifying observers, running a chosen algorithm, or executing a command. Variables like subject state, observers notified, strategy algorithm, and command object change step by step as shown in the execution table and variable tracker. Key moments include understanding why observers all get notified, how strategy changes behavior dynamically, and the role of command objects. The visual quiz tests understanding of these steps and variable changes. This helps beginners see how behavioral patterns work in practice.

Practice

(1/5)
1. Which behavioral pattern is used when an object needs to notify multiple other objects about a change in its state?
easy
A. Command
B. Strategy
C. Observer
D. Singleton

Solution

  1. Step 1: Understand the role of Observer pattern

    The Observer pattern allows one object (the subject) to notify many dependent objects (observers) automatically when its state changes.
  2. Step 2: Compare with other patterns

    Strategy selects algorithms at runtime, Command encapsulates requests, and Singleton restricts instance creation. Only Observer fits the notification role.
  3. Final Answer:

    Observer -> Option C
  4. Quick Check:

    Notification to many = Observer [OK]
Hint: Notification to many objects? Think Observer pattern [OK]
Common Mistakes:
  • Confusing Strategy with Observer
  • Thinking Command handles notifications
  • Mixing Singleton with behavioral patterns
2. Which of the following is the correct way to define a Command pattern interface in object-oriented design?
easy
A. An interface with a method like execute() to perform the action
B. A class that holds multiple algorithms to choose from
C. A subject that notifies observers about changes
D. A singleton class that manages global state

Solution

  1. Step 1: Identify Command pattern structure

    The Command pattern encapsulates a request as an object, typically by defining an interface with an execute() method to perform the action.
  2. Step 2: Eliminate other options

    A class that holds multiple algorithms to choose from describes Strategy, C describes Observer, and D describes Singleton, none of which define a command interface.
  3. Final Answer:

    An interface with a method like execute() to perform the action -> Option A
  4. Quick Check:

    Command interface = execute() method [OK]
Hint: Command pattern always has an execute() method [OK]
Common Mistakes:
  • Confusing Command with Strategy interface
  • Thinking Command notifies observers
  • Mixing Singleton with Command
3. Consider this code snippet using the Strategy pattern:
class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def execute(self, data):
        return self.strategy.do_algorithm(data)

class StrategyA:
    def do_algorithm(self, data):
        return sorted(data)

class StrategyB:
    def do_algorithm(self, data):
        return sorted(data, reverse=True)

context = Context(StrategyA())
result = context.execute([3, 1, 2])
print(result)

What will be the output?
medium
A. [3, 1, 2]
B. [1, 2, 3]
C. [3, 2, 1]
D. TypeError

Solution

  1. Step 1: Understand the Strategy pattern usage

    The Context uses StrategyA, whose do_algorithm method sorts the list in ascending order.
  2. Step 2: Trace the execution

    Calling context.execute([3, 1, 2]) calls StrategyA.do_algorithm which returns [1, 2, 3].
  3. Final Answer:

    [1, 2, 3] -> Option B
  4. Quick Check:

    StrategyA sorts ascending = [1, 2, 3] [OK]
Hint: StrategyA sorts ascending, so output is sorted list [OK]
Common Mistakes:
  • Assuming StrategyB is used
  • Confusing sorting order
  • Expecting original list unchanged
4. In the Observer pattern, what is the main issue if observers are not properly detached when no longer needed?
medium
A. Memory leaks due to lingering references
B. Strategy selection becomes unpredictable
C. Commands fail to execute
D. Singleton instance is duplicated

Solution

  1. Step 1: Understand observer detachment importance

    If observers are not detached, the subject keeps references to them, preventing garbage collection.
  2. Step 2: Identify consequence

    This causes memory leaks because unused observers remain in memory unnecessarily.
  3. Final Answer:

    Memory leaks due to lingering references -> Option A
  4. Quick Check:

    Undetached observers cause memory leaks [OK]
Hint: Undetached observers cause memory leaks [OK]
Common Mistakes:
  • Confusing with Strategy or Command issues
  • Thinking it causes command execution failure
  • Assuming Singleton duplication
5. You want to design a system where users can perform different operations (like save, load, delete) on files, and you want to queue these operations to execute later or undo them if needed. Which behavioral pattern best fits this requirement and why?
hard
A. Singleton pattern, because it ensures only one file manager exists
B. Observer pattern, because it notifies users about file changes
C. Strategy pattern, because it selects the best file operation algorithm
D. Command pattern, because it encapsulates requests as objects allowing queuing and undo

Solution

  1. Step 1: Analyze the requirement for queuing and undo

    Queuing operations and supporting undo requires encapsulating each request as an object to store and manage them flexibly.
  2. Step 2: Match with behavioral patterns

    The Command pattern encapsulates requests as objects, enabling queuing, logging, and undo functionality. Observer and Strategy do not support queuing commands, and Singleton only controls instance creation.
  3. Final Answer:

    Command pattern, because it encapsulates requests as objects allowing queuing and undo -> Option D
  4. Quick Check:

    Queue and undo operations = Command pattern [OK]
Hint: Queue and undo operations? Use Command pattern [OK]
Common Mistakes:
  • Choosing Observer for queuing commands
  • Confusing Strategy with Command
  • Selecting Singleton for operation management
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard