Object-Oriented Programming

Pattern: Dependency Injection

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Review: Strategy

  • Behavioral Pattern

  • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

  • AKA: Policy

Review: Strategy-Applicability

  • Many related classes differ only in behavior
  • Different variants of an algorithm are needed, often for different space/time tradeoffs
  • Algorithm uses data the client should not know about, or had dependencies we want to leave out of the client
  • A class has many behaviors, and there are multiple conditional statements in the operations. Move switch statement into its own Strategy class

Review: Strategy-Structure

Strategy Notes

  • All ConcreteStrategy’s have the same interface
  • Can change which ConcreteStrategy at any point during runtime

Dependency Injection

  • A broader form of Inversion of Control
  • Once chosen, it doesn’t tend to change during runtime
  • The primary purpose is for testing
  • Often extends the interface beyond that of the regular client

Original UML Sequence

originaluml

Original Code

Writing Tests

UML Sequence

UML Class Diagram

Client Code

Test Code (Attempt #1)

Test Code Solution

Comparison

  • Advantages
    • Decouples code
    • Allows for rich testing
    • Frameworks for creating mock objects
    • Each class has a more direct purpose
  • Disadvantages
    • Creates more classes
    • Obliged to do better testing
    • Introduces a controlled increase in complexity