Docsity

Strategy Pattern: Encapsulating Algorithms for Interchangeable Behavior, Study notes of Computer Science

Partial preview of the text

Download Strategy Pattern: Encapsulating Algorithms for Interchangeable Behavior and more Study notes Computer Science in PDF only on Docsity!

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

Motivation

Then you have different

types of Duck

So far, all ducks quack( )

and fly( )

Duck

Mallard^ Redhead

Motivation

Now RubberDuck

comes in

Duck

Mallard^ Redhead

Rubber

Duck

Motivation

You can expect more

weird ducks: some fly( )

but don’t quack( )

Solutions?

Push down fly( ) and

quack( ) and then

override?

Introduce interface?

Duck

Mallard^ Redhead

Rubber

Duck

Solution

fly( ) and quack( ) are the parts of the Duck

class that change

Create a new set of class to represent each

behavior

Code

public interface FlyBehavior { public void fly(); } public class FlyWithWings implements FlyBehavior { public void fly() { System.out.println("I'm flying"); } } public class FlyNoWay implements FlyBehavior { public void fly() { System.out.println("I can't fly") } }

QuackBehavior

quack()

Quack

quack( ) {

// open beak and

// make noise

Squeak

quack( ) {

// squeak! squeak!

MuteSqueak

quack( ) {

// do nothing

Code

public abstract class Duck { FlyBehavior flyBehavior; QuackBehavior quackBehavior; public Duck() { } public void setFlyBehavior (FlyBehavior fb) { flyBehavior = fb; } public void setQuackBehavior(QuackBehavior qb) { quackBehavior = qb; } abstract void display(); public void performFly() { flyBehavior.fly(); } public void performQuack() { quackBehavior.quack(); } public void swim() { System.out.println("All ducks float, even decoys!"); } }

Code

public class MallardDuck extends Duck { public MallardDuck() { quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } public void display() { System.out.println("I'm a real Mallard duck"); } }

ContextInterface() Context AlgorithmInterface() Strategy AlgorithmInterface() ConcreteStrategyA AlgorithmInterface() ConcreteStrategyB AlgorithmInterface() ConcreteStrategyC

UML

Final thoughts

Encapsulate what varies

Favor composition over inheritance

Program to interfaces, not implementations

Links

http://www.fluffycat.com/java/patterns.html

http://www.wickedlysmart.com/HeadFirst/

HeadFirstDesignPatterns/

HeadFirstPatternsIndex.html