Strategy Pattern in Java with real world example

Strategy Design Pattern defines a family of algorithms, encapsulates each one and makes them interchangeable. Subclasses decide how to implement steps in an algorithm.

Strategy Pattern is a behavioural design pattern. Often developer gets confused with Template Pattern and Starategy Pattern. For explanation I will use same example we used in Template with some changes in requirement. Let’s understand the Startegy pattern before jumping to difference between Teamplate Pattern and Strategy Pattern.

When To Use Strategy Design Pattern:

  1. When you want different variants of an algorithm.
  2. When many related classes differ only in their behavior.
  3. When a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals statements, move related conditional branches into their own Strategy class.
  4. When an algorithm uses data that clients shouldn’t know about. Use the Strategy Pattern to avoid exposing complex and algorithm-specific data structures.

Real World Example of Strategy Pattern:

  • Swing GUI Text components
  • Java AWT

Advantages of Strategy Pattern:

  • It provides an alternative to sub-classing the Context class to get a variety of algorithms or behaviors.
  • It eliminates large number of conditional statements.

Problems With Strategy Pattern:

  • Increases the number of objects.
  • All algorithms must use the same Strategy interface

An Example:
We want to develop a system to process flat files for: Stock and Derivatives.

Requirement:

  • Validate File type/format against system configuration
  • Stock or Derivative data can be stored in database or content repository (e.g. XML)
  • File can be routed to third party system Capital IQ(via SOAP) or other customers (e.g. JMS)
  • Investment Bank can do the below action:

City Bank: validate, store (Repo) and route to Capital IQ
ICICI Bank: validate, store data(database) and route to Capital IQ
Axis Bank: validate, store data and route to other customer