Strategy Pattern

This is an introduction to Strategy Design Pattern.

What is Strategy Design Pattern

Concept

defines a family of algorithms,
encapsulates each one, and makes them interchangeable.
Strategy lets the algorithm vary independently from
clients that use it.

Key Points

  1. Base class extends to various child class type, children share/vary some behaviors
  2. For shared behaviors, implement in base class
  3. For varied for each typed class, implement in child class
  4. For behaviors some children share, some vary,
    • declare instance variables in base class,
    • interface types,
    • determine specific behaviors at runtime,
    • can change dynamically by set methods.

duck example

Requirements: a duck game with many kinds of different ducks.
Shared behaviors: swim
Behaviors varied each type: display
Behaviors some vary, some share: fly, quack

The first 2 kinds of behaviors are easy to handle:
shared swim: implement in base class
varied display: implement in each child class type.

The key is to design the 3rd kind of behavior.

Here is 3 different kinds of design:

inheritance

Implement fly/quack in base class as pic below, then all children type shares same behaviors. Not working!
Implement fly/quack in each child class, it works, but lots of duplicate code.
Inheritance Duck

interface

All child classes have to override fly/quack interface, tons of duplicate work.
Interface Duck

strategy pattern

Perfect way so far!
keep shared behaviors to reduce code work.
Instance variables from interfaces enables us to encapsulate just a couple of fly/quack behaviors to apply on all child classes.
Moreover, dynamic set methods in base class enable us dynamically change fly/quack behaviors.
Strategy Pattern Duck

My Code Example

https://github.com/AudreyMeng/Java/tree/master/StrategyPattern

Reference

Head First Design Pattern