strategy

Strategy Pattern
Strategy Pattern

Intent

Define a family of algorithms, encapsulate each
one,and make them interchangeable. Strategy lets
the algorithm vary independently from clients that
use it.

Also known as “Policy”

Motivating example

Different line break algorithms for varying types of
text
SimUDuck example

Joe works for a company that makes a highly
successful duck pond simulation game,
SimUDuck. The game can show a large variety
of duck species swimming and making
quacking sounds.
Inheritance based design
Inheritance based design
Now RubberDuck can fly!
What about using Interface?
What about using Interface?
Duplicated code!
Now try changing fly().
Encapsulate Behaviors

Separate them out of the client

Define as interfaces
Delegate behaviors
Strategy Pattern
Design Principles

Identify the aspects of your application that vary
and separate them from what stays the same.

Program to an interface, not an implementation.

Favor composition over inheritance

Has-A is better than Is-A
Strategy Pattern in FP

Different strategies are just different functions

Higher order functions (HOF)


Function is first -class, can live alone and be
passed around
In OOP, method is not first-class, must be
encapsulated in a class (“world of nouns”)
What about polymorphism?

Dispatch on type


Calling different functions according to the data type
In Clojure

Custom data type: defrecord

Custom behavior groups (interface): defprotocol

Don't support inheritance