Week 05 Tutorial

H12A

Strategy
Observer
State

Design Patterns: The Origin Story

Design Patterns: The Origin Story

The Gang of Four

Strategy Pattern

Key Characteristics

  • Defines a family of algorithms
  • Encapsulates each algorithm
  • Allows algorithms to be interchangeable

private SortStrategy strategy;

BubbleSort

BubbleSort

MergeSort

QuickSort

HeapSort

Strategies

DataSorter

<<SortStrategy>> {sort()}

private SortStrategy strategy;

strategy.sort();

void setStrategy (SortStrategy);

Strategy Pattern

When to Use

  • You need different variants of an algorithm
  • You want to avoid multiple conditionals in your code.
  • You have a set of related classes that differ only in their behaviour

State Pattern

Key Characteristics:

  • Allows an object to change its behaviour when its internal state changes
  • Encapsulates state-specific behaviour in separate classes
  • Transitions between states are typically managed by the state classes themselves

State Pattern

When to Use

  • An object’s behaviour depends on its state, and it must change its behaviour at runtime depending on that state
  • Operations have large, multipart conditional statements that depend on the object’s state 

The crucial difference

While both patterns involve changing an object’s behavior, the key difference lies in their intent:

  • Strategy focuses on making algorithms interchangeable.
  • State focuses on allowing an object to change its behaviour when its internal state changes.

Breaking LSP 🐣

  • Give an example of a real-life subclass that would violate the given contract:

List<String> singers = List.of("Taylor Swift", "Jimi Hendrix", "Beyoncé", "Tyler the Creator", "Adele");

List<String> lineup = singers.stream()
    .filter(s -> hasGrammy(s))     // 🎤 Filter Grammy winners
    .map(s -> styleOutfit(s))      // 💄 Give stage outfit
    .toList();                     // 🚌 Collect them for their performance

Note: by real-life subclass, I mean some kind of creature that is a type of Bird.

Observer Pattern

Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.

Week 05 Tutorial

By esha tripathi

Week 05 Tutorial

  • 54