Strategy Design Pattern

Design patterns are better understood when we try learning them with an example. Lets take up a problem here.

Problem:

Lets say there are Animals which can fly and those which cannot. Since, the world is constantly evolving, any animal can be given the ability to fly by nature, or the ability can be taken from the animal.

Design:

The problem that the great mathematician ‘Nature’ faces here is, ‘How to incorporate a new behavior of flying within the present evolution scenario?’. Nature will have to ensure that the flying abilities can be altered and changed with time, in order to ensure that evolution is not compromised.

Steps nature followed – 

  1. Prepare various flying algorithms (NoFlyingAbility, SparrowLikeFylingAbility, EagleLikeFlyingAbility) under a common interface FlyingAbility.
  2. The FlyingAbility interface was added to Animal abstract class. This means that Animals can now have FlyingAbiltiy.
  3. A public setter of FlyingAbility in Animal ensures that evolution can surely update the flying capabilities of the Animals.

This pattern is called StrategyPattern as the nature decides the strategy an animal will use to fly.

Class Diagram

«Click on the image for a larger view»

image

Download the coded implementation


https://github.com/73ddy/design_patterns/tree/master/StrategyPattern

Pros and Cons


Advantages:

  1. The algorithms and behaviors can be reused.
  2. The algorithms are loosely coupled with the context entity. They can be changed/replaced without changing the context entity.
  3. Prevents the conditional statements.

Disadvantages:

  1. Client must be aware of the various strategies, thus helping him decide the best strategy.
  2. It increases the number of objects in the application.
Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: