Strategy Design Pattern

Vivek ChincholiVivek Chincholi
2 min read

This Article is a continuation of our Design pattern series, here we are with another design pattern “Strategy Design Pattern“, for better understanding please check my posts on linkedin.

Now, Lets Consider We wanted to add a dive functionality to some boats. The two methods, inheritance and method overriding did not serve our purpose. cause boat which are non able to dive they also inherit the dive characteristics. so here we go the solution using strategy pattern.

If you recall the design principle, we need to separate the changing code from what already exists. The only part changing is the dive() behaviour, so we create an interface Diveable and create two more classes that implement it.

interface Diveable {
    public void dive();
}
class DiveBehaviour implements Diveable {
    public void dive() {
      // Implementation here
    }
}
class NoDiveBehaviour implements Diveable {
    public void dive() {
       // Implementation here
    }
}

Now, in your Boat class, create a reference variable for the interface and have a method performDive() that calls this dive() method.

abstract class Boat {
    Diveable diveable;
    void sway() { ... }
    void roll() { ... }

    abstract void present();

    public void performDive() {
        diveable.dive();
    }
}

The FishBoat and DinghyBoat classes aren’t supposed to have the dive behaviour, so they’ll inherit the NoDiveBehaviour class. Let’s see how.

class FishBoat extends Boat {
    ...

    public FishBoat() {
        diveable = new NoDiveBehaviour();
    }
    ...
}

When the reference variable diveable is instantiated to the NoDiveBehaviour object, the FishBoat class inherits the dive() method from this class.

For the new class SubBoat, a new behaviour can be inherited.

class SubBoat extends Boat {
    ...  

    public FishBoat() {
        diveable = new DiveBehaviour();
    }
    ...
}

Now, let’s test the functionality.

Boat fishBoat = new FishBoat();
fishBoat.performDive();

When performDive() is called, it calls the dive method of the NoDiveBehaviour class.

Boat subBoat = new SubBoat();
subBoat.performDive();

This performs a completely different action as it calls the actual dive behaviour. Hence, our new boat turns into a submarine and takes a dive.

Hope you got clear!,
See you later alligator..!

0
Subscribe to my newsletter

Read articles from Vivek Chincholi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vivek Chincholi
Vivek Chincholi