Strategy Design Pattern in Java

The strategy pattern is a behavioral design pattern that enables an algorithm’s behavior to be selected at runtime without causing tight coupling. The strategy pattern defines a family of algorithms, encapsulates each algorithm, and makes algorithms interchangeable. Strategy pattern lets the algorithm vary independently from clients that use it.

For more information go to http://en.wikipedia.org/wiki/Strategy_pattern

The definition in original Gang of Four book is given below

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Class Diagram

Strategy Pattern in Java

Example

Suppose we can have slightly different temperatures at different time(i.e., morning, noon, afternoon, evening etc.) in a day. So we do not know what would be the temperature at different time, until we reach to morning or evening, that is, run-time. This is the whole point of Strategy pattern.

Implementation

Define a interface DayTemperature, which has one method displayTemperature()

Now we have several kinds of day time.

Define a day time in when temperature gets changed.

Run the above test class and see the below output in the console

That’s all. Thanks for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.