Introduction to Strategy Design Pattern

Sep 11, 2024

Design Patterns Lecture Notes

Introduction to Design Patterns

  • Focus on design patterns as described in the book.
  • A total of thirteen patterns will be covered.
  • Recommended for beginners: Illustrated and pedagogical book.
  • Not suitable for those looking for strict definitions and UML diagrams.

Pattern 1: Strategy Pattern

Overview

  • Sensible starting point for learning design patterns.
  • Simplest pattern focused on composition over inheritance.
  • Key takeaway: Inheritance is not meant for code reuse.

Official Definition (from the book)

  • Defines a family of algorithms.
  • Encapsulates each algorithm and makes them interchangeable.
  • Allows algorithms to vary independently from clients.

Key Concepts

  • Decoupling algorithms from clients.
  • Clients refer to the algorithms without being affected by changes in the algorithms.
  • Example: A collection with an injectable sorting strategy.

Example: Duck Class

  • Duck Superclass: Intended for inheritance by other classes.
    • Example subclasses: Wild Duck and City Duck.
  • Subclasses implement their own display method.
  • All ducks share the same quack method.

Issue with Inheritance

  • Inheritance can lead to issues when requirements change.
  • Example: Adding a fly method leads to complications with subclasses like Rubber Duck.
  • Risk of code duplication when behavior traits vary.

Transition to Strategy Pattern

  • Extract algorithms (e.g., quack and fly).
  • Implement interfaces for behaviors:
    • IQuackBehavior
    • IFlyBehavior
  • Ducks must have concrete implementations of these behaviors.

Implementation Steps

  1. Create interfaces for behaviors.
  2. Implement concrete classes for specific behaviors (e.g., SimpleQuackBehavior, NoQuackBehavior).
  3. Modify Duck class to use injected behaviors rather than hard-coded methods.

Example Code Concepts

  • Duck Class:
    • Properties for flyBehavior, quackBehavior, displayBehavior.
    • Constructor accepts and sets behaviors.
    • Methods delegate to behaviors.
  • Concrete Behavior Classes: Implement interfaces with specific algorithms.

Generalized UML Diagram of Strategy Pattern

  • Client (Duck) has an interface reference.
  • Interface can be implemented by multiple concrete behaviors.
  • Allows interchangeable behaviors.

Conclusion

  • Strategy pattern allows for flexible designs where behaviors can vary independently.
  • Encouraged to read the book for deeper understanding.
  • Next lecture will cover the next design pattern in the series.