Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism vs Strategy pattern

What is the difference between the Strategy pattern and Polymorphism in Java?

I'm confused that whatever is achieved via Strategy Pattern is basically possible by polymorphism. Correct me if I'm wrong in this regard.

Please, also provide me example to eradicate my confusion.

like image 808
TryinHard Avatar asked Jul 24 '15 11:07

TryinHard


People also ask

Does Strategy pattern use polymorphism?

In short, a strategy pattern can use polymorphism.

What is the difference between strategy and bridge pattern?

While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure. The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

What is the difference between strategy and decorator pattern?

The strategy pattern allows you to change the implementation of something used at runtime. The decorator pattern allows you augment (or add to) existing functionality with additional functionality at run time.


3 Answers

For me, the link from CKing post and the example in Wikipedia are clear enough, but I'll try to give you a new example. As they said, Strategy Pattern is mostly a way to change the behaviour of an algorithm at runtime. Of course you can achieve this in many different ways (such as holding a value and using switch-case, but it wouldn't be as nice as Strategy Pattern).

Let's say you're developing a turn-based strategy game with two kind of Units: Infantry and Tank (subclasses of Unit). Your terrain could be Plains, Railroad or Forests.

class Unit{
    MovementStrategy ms;      
    final int baseMovement;
    int x,y;

    public Unit(int baseMovement){
        this.baseMovement = baseMovement;
    }

    abstract void fire();

    void moveForward(){
        x = x + ms.getHexagonsToMove(baseMovement);
    }

    void setMovementStrategy(MovementStrategy ms){
        this.ms = ms;
    }
}

Any Unit subclass must implement fire() method because it's going to be completely different for them (Tank shots heavy long-distance round and Infantry shot several short distance light bullets). In this example we use normal polymorphism/inheritance since fire() method will be really different for any unit, and it won't change during the game.

class Infantry extends Unit{
    public Infantry(){
        super(2);
    }

    void fire(){
        //whatever
    }
}

class Tank extends Unit{
    public Tank(){
        super(5);
    }

    void fire(){
        //whatever
    }
}

Units also are able to move, and have a field baseMovement that holds the number of hexagons it can walk. We're developing a strategy game, not a real world simulation, so we don't care how they move, we just want to add a value to their coordinates (in my example I only use X coordinate in order to get a simpler code). If all the terrain was the same, we wouldn't need any Strategy object... but we need to change the behaviour of move() method at runtime!

So, we implement a different MovementStrategy class for each of our kinds of Terrain, and we program our game to trigger a setMovementStrategy() to any unit that move on each hexagon. And we don't even need to write anything else in our Unit subclasses.

interface MovementStrategy{
    public int getHexagonsToMove(int base);
}

class PlainMovementStrategy implements MovementStrategy{
    public int getHexagonsToMove(int base){
        return base;
    }
}

class RailroadMovementStrategy implements MovementStrategy{
    public int getHexagonsToMove(int base){
        return base*3;
    }
}

class ForestMovementStrategy implements MovementStrategy{
    public int getHexagonsToMove(int base){
        return (int)(base/2);
    }
}   

Now, when any Unit move inside a Forest, we call

unit.setMovementStrategy(new ForestMovementStrategy());

And as soon it goes to a Plain, we do:

unit.setMovementStrategy(new PlainMovementStrategy());

Now we're able to change how far away our units move depending on the Terrain, and we don't need to rewrite in any of the subclasses.

I hope this helps you a better understanding of the difference.

like image 193
rolgalan Avatar answered Sep 26 '22 00:09

rolgalan


I'm confused that whatever is achieved via Strategy Pattern is basically possible by polymorphism.

You can't drive a car without a steering wheel. That does not mean that a steering wheel is a car. Similarly, the Strategy pattern relies on polymorphism but that does not mean that they are the same thing.

The purpose of the Strategy pattern is to promote the use of composition (has-a) over inheritance (is-a). Instead of your class inheriting behavior from a super class, you define the behavior in a separate class and your class has-a reference to it.

As far as an example goes, take a look at this answer that does a good job.

like image 25
Chetan Kinger Avatar answered Sep 25 '22 00:09

Chetan Kinger


  • Basic difference : Polymorphism is programming language concept, and Strategy pattern is one of behavioral design pattern of GoF.

  • Polymorphism is the provision of a single interface for several different underlying data types.

    • Example: The steering wheel(i.e., the interface) is same no matter what type of actual steering mechanism is used. That is, the steering wheel works the same whether your car has manual steering, power steering, or rack-and-pinion steering. Therefore once you know how to operate the steering wheel, you can drive any type of car.

    • In programming, Polymorphism implemented in two ways:

      • Early-Binding/Static/Compile-Time Polymorphism (ex: function overloading)
      • Late-Binding/Dynamic/Run-Time Polymorphism (ex: function overriding)
  • A Strategy pattern defines a set of algorithms that can be used interchangeably.

    • The Strategy pattern is a dynamic pattern (How do you want run a behavior in software?).

    • Example of core java: java.util.Comparator#compare(), executed by among others Collections#sort().

    • Modes of transportation is analogous to strategy design pattern. We use car, bike, bus, local train and so on.. different strategies to go office day by day.

like image 36
Premraj Avatar answered Sep 23 '22 00:09

Premraj