Strategy Pattern

Problem Statement:

We have a duck class using inheritance as below. We want to make duck fly. How?

Added fly() in superclass. All duck can use the fly() method.

Code reuse!

BUT!!!

Not all duck can fly.

PROBLEM!

What can we do? 

Override??

But what happen when we add wooden decoy ducks?

How about if we use interface?

if we write like this, what will be happened? 

1.  X Inheritance - not all of the subclasses should have flying or quacking behavior

 

2. X interface - Implement of Flyable and Quackable solves the problem but it destroys code reuse

HOW?

Strategy Pattern

Here come with our ...

First!

We need to separate the changes from the same

We create 2 interfaces.

FlyBehavior and QuackBehavior

With this design, other types of objects can reuse our fly and quack behavior.

We can add new behaviors without modifying existing classes.

Define MallarDuck ...

Main class ...

Output:

Quak

I'm flying

We can set the behavior dynamically...

by adding these method

Main class ...

Output:

Quak

I'm flying!!

I can't fly

I'm flying with a rocket

Overview picture...

DEMO

Strategy Pattern

defines a family of algorithms, encapsulates each one, and makes them interchangeable.

 

Strategy lets the algorithm vary independently from client that use it.

Strategy Pattern

Strategy pattern using HAS-A relationship.

Each duck has a FlyBehavior and a QuackBehavior.

 

When we put 2 classes together, we are using composition.

 

Create system using composition gives us a lot more flexibility. It can let us change behavior at runtime.

Strategy Pattern

By shirlin1028

Strategy Pattern

  • 270