Strategy

Strategy
Qiyuan An
Mingyu Fan
Qi Tan
Duck
Duck
Duck
Intent
• Define a family of algorithms, encapsulate each one, and make
them interchangeable.
• Strategy lets the algorithm vary independently from clients that
use it.
Motivation
• If the clients include concrete implementation of flying and
quacking, clients will be bigger and harder to maintain.
Motivation
• We can choose the appropriate algorithm and ignore those we
don’t use.
Applicability
• many related classes differ only in their behavior.
• you need different variants of an algorithm.
Applicability
• an algorithm uses data that clients shouldn't know about.
• a class defines many behaviors, and these appear as multiple
conditional statements in its operations.
Structure
Participants

Strategy (FlyBehaviour/QuackBehaviour)


ConcreteStrategy (FlyWithWings..)


Declares an interface common to all supported algorithms.
Context uses this interface to call the algorithm defined by a
ConcreteStrategy.
Implements the algorithm using the Strategy interface.
Context (Duck)

It is configured with a ConcreteStrategy object.

It maintains a reference to a Strategy object.

It may define an interface that lets Strategy access its data.
Collaborations


Strategy and Context interact to implement the
chosen algorithm.
A context forwards requests from its clients to its
strategy.
Collaborations
Consequences
• Benefits:
• Families of related algorithms.
• An alternative to subclassing.
• A choice of implementations.
• Strategies eliminate conditional statements.
• Drawbacks:
• Clients must be aware of different strategies.
• Communication overhead between Strategy and
Context.
• Increased number of objects.
Consequences
•
Benefits:
•
Families of related algorithms.
Help factor out common functionality of the algorithms.
•
•
An alternative to subclassing.
More choices of implementations.
Consequences
•
Benefit:
•
Strategies eliminate conditional statements.
Consequences

Drawbacks:

Clients must be aware of different strategies.

Communication overhead between Strategy and Context.

Increased number of objects.
Possible solution: flyweight pattern.
Related Patterns
Flyweight: Strategy objects often make good flyweights.
Flyweight pattern
Strategy pattern
Related Patterns
State pattern: similar structure
State pattern
Strategy pattern
Known users


ET++ and InterViews: linebreaking algorithms.
RTL System for compiler code optimization(different machine
architectures):
Register allocation schemes and instruction set scheduling policies

RApp: for integrated circuit layout: Routing algorithms.

Others:

ET++ SwapsManager calculation engine framework.

Booch components: as template arguments.

Borland’s ObjectWindows.
Reference


Head First Design Patterns
http://www.cnblogs.com/justinw/archive/2007/02/06/
641414.html
Q and A