The Strategy Pattern
1
The Strategy Pattern Jay Urbain, Ph.D. urbain@msoe.edu 1 Review - - PowerPoint PPT Presentation
The Strategy Pattern Jay Urbain, Ph.D. urbain@msoe.edu 1 Review What problems are we trying to avoid? 2 Review What problems are we trying to avoid? l Class explosions l Code duplication l Tight Coupling l Poor Cohesion What
1
2
l Class explosions l Code duplication l Tight Coupling l Poor Cohesion
3
l Class explosions l Code duplication l Tight Coupling l Poor Cohesion
l Modifiable behaviors l Ease of maintenance l High cohesion l Loose coupling
4
5
<<abstract>> Duck Mallard
Duck Mallard(name: String) : void
SimUDuck v5 + urbain version
Collections.sort() uses a reference
to a concrete class that implements the Comparable interface, and thus the behavior of the compare() method. Depending on the strategy of the compareTo() method in the concrete class, different sorting will be used by Collections.sort(). The comparison strategy is decoupled from the Collections.sort() method itself.
6
7
// method prototype void Collections.sort(List<T> list) // usage: get highest priority type for domain Collections.sort( freebaseMqlEntityList ); Implementation: public class FreebaseMqlEntity implements Comparable<FreebaseMqlEntity> {
@Override public int compareTo(FreebaseMqlEntity arg0) { if( this.getPriority() < arg0.getPriority() ) { return -1; } else if( this.getPriority() > arg0.getPriority() ) { return 1; } else { return 0; } }
ConcreteStrategy classes implement specific behaviors The Context is the class that encapsulates and uses a specific behavior, or Strategy. A Strategy is an interface that defines a behavior
9
10
11
<<abstract>> Duck Mallard
Duck Mallard(name: String) : void
SimUDuck v5 + urbain version
12
public abstract class Duck{ SwimBehavior sb; QuackBehavior qb; String name; // constructor public void Duck(String name, SwimBehavior sb, QuackBehavior qb) { this.name = name; swimBehavior = sb; quackBehavior = qb; } // centralize implementation of behaviors in top-level classes // avoid duplication of behavior in subclasses. public void swim() { swimBehavior.swim(); // invoke the specific behavior } ...
13
i.
ii.
iii.
l We can select particular behavioral strategies when
l And since the swim() or quack() behaviors of Duck are
l Instead of changing the behavior implemented within a
l The Strategy pattern lets us vary and change behavioral
1.
2.
17
l If “yes”, then it has high coupling (bad) l Changing swim or quack behaviors does not require
18
l Decreases coupling, increases cohesion l The behavior of the Duck is not coupled to the Duck –
l Like all Design Patterns, the Strategy pattern allows
l Yes: the implementation of the Strategy Pattern is
l All design patterns usually exhibit this type of tradeoff.
20
l Code to the most restrictive level of access modification that
i.
ii.
iii.
iv.