DEV Community

Daniel Lee
Daniel Lee

Posted on • Updated on

Design Pattern: The Strategy Pattern

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm very independently from clients that uses it. Then, what strategies are out there?

  1. Identify the aspects of your application that vary and separate them from what stays the same

    • For example, create a new set of classes for what's changing infrequently and what changes frequently. In this way, you can scale and design your program flexibly.
  2. Program to an interface, not an implementation

    • Programming to an interface means programming to a supertype. A supertype is a generic entity type that has a relationship with one or more subtypes. For instance, you can identify relationships between entities: HAS-A, IS-A, IMPLEMENTS, etc.

  • A behaviour-focused class should implement a particular behaviour interface; delegate behaviours instead of using methods in the class or subclass
  1. Favour Composition over inheritance

    • Identifying relationships makes it easy to compose your program and encapsulate a family of algorithm into their own set of classes
    • A benefit of such strategy is that it can change the behaviour of your application at runtime: call only what's needed

Discussion (0)