the strategy pattern

21
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1

Upload: carla-wong

Post on 03-Jan-2016

19 views

Category:

Documents


0 download

DESCRIPTION

The Strategy Pattern. Review. What problems are we trying to avoid?. Review. What problems are we trying to avoid? Class explosions Code duplication Tight Coupling Poor Cohesion What do we want to achieve?. Review. What problems are we trying to avoid? Class explosions - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: The Strategy Pattern

The Strategy Pattern

SE-2811Dr. Mark L. Hornick

1

Page 2: The Strategy Pattern

Review

What problems are we trying to avoid?

SE-2811Dr. Mark L. Hornick

2

Page 3: The Strategy Pattern

ReviewWhat problems are we trying to avoid? Class explosions Code duplication Tight Coupling Poor Cohesion

What do we want to achieve?

SE-2811Dr. Mark L. Hornick

3

Page 4: The Strategy Pattern

ReviewWhat problems are we trying to avoid? Class explosions Code duplication Tight Coupling Poor Cohesion

What do we want to achieve? Modifiable behaviors Ease of maintenance High cohesion Loose coupling

SE-2811Dr. Mark L. Hornick

4

Page 5: The Strategy Pattern

A different approach: Isolate behaviors that vary, and encapsulate them as attributes to eliminate implementation inheritance and class explosions:

SE-2811Dr. Mark L. Hornick

5

SimUDuck v5

Page 6: The Strategy Pattern

Consider Collections.sort()

Collections.sort() implements an argument which is a reference to a concrete class that implements the Comparator interface, and thus the behavior of the compare() method.

Depending on the strategy of the compare() method in the concrete class, different sorting will be used by Collections.sort().

The comparison strategy is decoupled from the Collections.sort() method itself.

SE-2811Dr. Mark L. Hornick

6

Page 7: The Strategy Pattern

The Strategy Design Patternin its general form:

ConcreteStrategy classes implement specific behaviors

The Context is the class that encapsulates and usesa specific behavior, or Strategy.

A Strategy is an interfacethat defines a behavior

Page 8: The Strategy Pattern

Applying the Strategy Pattern: step 1The Strategy Pattern is a behavioral pattern usually considered and applied at design-time.

Premise: Your application requires similar objects whose behavior varies.

SE-2811Dr. Mark L. Hornick

8

Page 9: The Strategy Pattern

Applying the Strategy Pattern: step 2

As a designer, you watch for inheritance patterns that result in excessive behavior overrides and/or code duplication among classes.

SE-2811Dr. Mark L. Hornick

9

Page 10: The Strategy Pattern

Applying the Strategy Pattern: step 3Leave behavior that is truly shared in abstract classes.

Isolate behavior(s) that vary and declare interfaces that define those behaviors

Implement the behaviors in separate concrete classes whose references can be passed to the Duck ctor

SE-2811Dr. Mark L. Hornick

10

Page 11: The Strategy Pattern

Creating Ducks with specific behaviors

// create some behaviorsSwimBehavior csb = new CircularSwimming();QuackBehavior sqb = new StandardQuacking();SwimBehavior rsb = new RandomFloating();

// daffy has circular swimming, std quackingWaterfowl daffy = new Duck(“daffy”, csb, sqb);// donald has random floating, std quackingWaterfowl donald = new Duck(“donald”, rsb, sqb);daffy.swim();donald.quack();

SE-2811Dr. Mark L. Hornick

11

Page 12: The Strategy Pattern

Inside a Duck class

// constructorpublic void Duck(String name, SwimBehavior sb, QuackBehavior qb) {super(name, sb, qb)

}

SE-2811Dr. Mark L. Hornick

12

Page 13: The Strategy Pattern

Inside a Waterfowl classpublic abstract class Waterfowl {

private SwimBehavior swimBehavior; private QuackBehavior quackBehavior;private String name;// constructorpublic void Waterfowl(String name, SwimBehavior sb,

QuackBehavior qb) {this.name = name;swimBehavior = sb;quackBehavior = qb;

} // centralize implementation of behaviors in top-level classes // if possible; avoid duplication of behavior in subclasses. // Note we can make this method final to prevent subclasses

from overriding it!public void swim() {

swimBehavior.swim(); // invoke the specific behavior}

...

SE-2811Dr. Mark L. Hornick

13

Page 14: The Strategy Pattern

Strategy is a Behavioral Design Pattern

The Strategy pattern allows for selection of specific behavioral algorithms at runtime, since the selected strategy is just an attribute of the class using the Strategy. We can select particular behavioral strategies when

we constructed the Ducks But since the swim() or quack() behaviors of Duck are

just attributes (references) to concrete Strategy classes, we could easily change the behaviors at any time with a simple setSwimBehavior() mutator method!

Page 15: The Strategy Pattern

The Strategy pattern favors Encapsulation over Extension

That is, rather than changing the behavior implemented within a derived class by extending from a parent/base class, we encapsulate behaviors into a class as instance attributes, which can be varied.

The Strategy pattern lets us vary and change behavioral algorithms independently of the clients that use the behaviors.

Page 16: The Strategy Pattern

A good Design Pattern has also solved a larger conceptual issue:

To make a program easy to maintain, we always want to strive for

1. High cohesion

2. Low coupling

SE-2811Dr. Mark L. Hornick

16

Page 17: The Strategy Pattern

Coupling: How closely two or more classes are related

Does changing code in one class require changes in another class?? If “yes”, then it has high coupling (bad) Changing swim or quack behaviors does not require

changes to the Duck class (low coupling)

SE-2811Dr. Mark L. Hornick

17

Page 18: The Strategy Pattern

Other design principles benefitting from the Strategy Pattern

Decreases coupling, increases cohesion The behavior of the Duck is not coupled to the

Duck – behaviors are implemented separately. Like all Design Patterns, the Strategy pattern

allows us to vary a part of the system (swim and quack behavior) independently of other parts

Page 19: The Strategy Pattern

Other good design principles we visited

Code to the highest level of abstraction that is possible in a given context:i. ArrayList<Thing> = new ArrayList<Thing> // bad

ii. List<Thing> = new ArrayList<Thing> // good

iii. Collection<Thing> = new ArrayList<Thing> // better

Page 20: The Strategy Pattern

Other good design principles we visited Code to most restrictive level of access

modification that is possible in a given context:i. Use public for constants and methods; never for

attributes. On methods: only on those you want to support for public consumption

ii. Use /*package*/ if cooperating classes in the same package need access to attributes or special methods

iii. Use protected to allow derived classes in any package access to members

iv. Use private to completely guard members from view outside the defining class

Page 21: The Strategy Pattern

Are there disadvantages?

Yes: the implementation of the Strategy Pattern is somewhat more sophisticated than using simple inheritance All design patterns usually exhibit this type of

tradeoff.

SE-2811Dr. Mark L. Hornick

21