Java Design Pattern: Strategy Pattern



One of the most popular patterns is the Strategy Pattern. It is also one of the easiest patterns.

It is a member of the behavioral patterns family, it has the duty of managing algorithms, relations and responsibility among classes. The GoF defines it as follow:

It defines a series of encapsulated algorithms that can be exchanged for specific behaviors.

Let's look the UML diagram:

Strategy Pattern UML

We can notice that the Context, which can be imagined as every entity that need a "dynamic" behavior, is composed of a Strategy.

Why is Strategy an interface? Because the ConcreteStrategy will implement this interface so, when we will decide to change the implementation of the concrete classes, the Context's structure will not change.

Speaking about classes that are already present in some Java libraries, the java.awt.Container components are an example of Strategy Pattern, in fact the LayoutManager acts as Strategy class and the classes like BorderLayout and FlowLayout implement LayoutManager, implementing the method addLayoutComponent(). The different implementations differ in the way and position of the object that will be placed in the container. The Container class contains the LayoutManager object.

Other examples are:

  • java.util.Comparator#compare() called by Collection.sort();
  • javax.servlet.http.HttpServlet: service() method with every method doXXXX() that accept HttpServletRequest and HttpServletResponse as parameters;
  • javax.servlet.Filter#doFilter();

Let's look in details every component of the pattern.

  • Strategy: it is the interface that declares the family of algorithms and that is used from Context to invoke a concrete algorithm;
  • Context: context class that invokes the ConcreteStrategy. It can expose an interface to allow ConcreteStrategy to access any internal data structures;
  •  ConcreteStrategy: they are the implementation of the algorithms that Strategy exposes;

Let's try to understand the structure of the pattern.

Strategy

public interface Strategy{
     public void execute(paremeters);
}

ConcreteStrategy

public class ConcreteStrategyA implements Strategy{
  @Override
  public void execute(parameters){
   //implementation
  }
}
public class ConcreteStrategyB implements Strategy{
  @Override
  public void execute(parameters){
   //implementation
  }
}

Context

public class SortingContext {   
  private Strategy strategy;
  public void setMethod(Strategy strategy) {
   this.strategy = strategy;
  }   
  public Strategy getStrategy() {
   return strategy;   
  }   
  public void doMethod(paremters){
   strategy.execute(parameters);   }
}

I want to precise that I am showing a general structure and the interface has only one method so the concrete classes will overwrite only one method. The pattern can be extended by exposing more than one abtract method and the way of working will remain the same. The code would be longer, but not necessarily more complex.


Let's look to a scheme that shows how a client puts into action the Strategy Pattern:

Strategy pattern in action

Here is an example that uses some different sorting algorithm applying the Strategy Pattern.

Strategy

public interface SortingStrategy{
     public void sort(int[] v);
}

ConcreteStrategy

public class SelectionSort implements SortingStrategy{
     @Override
     public void sort(int[] v){
        System.out.println("Selection Sort!");
        int first;
        int temp;
        for (int index = v.length - 1; index > 0; index--) {
           first = 0;
           for (int j = 1; j <= i; j++) {
           if (v[j] > v[first])
              first = j;
           }
        temp = v[first];
        v[first] = v[index];
        v[index] = temp;
        }
     System.out.println(Arrays.toString(v));
  }
}

public class InsertionSort implements SortingStrategy {
  @Override
  public void sort(int[] v) {
     System.out.println("Insertion Sort!");
     for (int index = 1; index < v.length; index++) {
        int temp = v[index];
        int j;
        for (j = index - 1; (j >= 0) && (v[j] > temp); j--) {
           v[j + 1] = v[j];
        }
        v[j + 1] = temp;
     }
  System.out.println(Arrays.toString(v));
  }
}

Context

public class SortingContext {
  private SortingStrategy strategy;
  public void setSortingMethod(SortingStrategy strategy) {
     this.strategy = strategy;
  }
  public SortingStrategy getStrategy() {
     return strategy;
  }
  public void sortNumbers(int[] v){
     strategy.sort(v);
  }
}

Let's understand the code

  • SortingStrategy: it has the classic behavior of the Strategy interface described before, in fact it exposes a method that represents the algorithm to implement;
  • SelectionSort/InsertionSort: it plays the role of ConcreteContext. This is because implementing SortingStrategy they override the method, defining an implementation of the desired sorting algorithm;
  • SortingContext: it plays the role of Context, exposing a SortingStrategy object that will later become an instance of one of the concrete classes;

Why sould you use the Strategy Pattern?

Sometimes we can have very complex situations where using inheritance mechanisms would generate very long and complex hierarchies. This pattern allows us to reduce considerably the complexityof the code. On the other hand, every client that uses the Context class must know the best Strategy to use.

Someone could ask spontaneously: "you showed me a canonical example with sorting algorithms. Where is it used practically?".

The use cases are manifold. We can think of data compression software, which allow us to choose between different compression formats. Another example is a payment platform where you can hypothetically choose the payment method to be used and so on.

These cases, like many others, use the Strategy Pattern.

We must precise that in a lot of cases organizing very well the pattern could not be trivial.

Some observations

Ultimately, we have defined a general structure of the model, giving the general construction of the various components and then giving a practical example.

In my opinion for any programmer who wants to approach a professional programming this is a pattern that must be known. It allows us to linearize so many situations that taking advantage of the common mechanisms that we are sometimes taught in high schools, such as heredity, would be much more complicated.

Talking a llittle bit about theoretical computer science, this pattern uses the mechanism of polymorphism made available by the presence of the interfaces that we use as Strategy. The importance of having a generic interface, as told before, is to be able to change the behavior of ConcreteStrategy without changing the structure of the class itself, in fact we also take advantage of the possibility of having an apparent type different from the real type of the class. In fact, as we know in Java it is legitimate to declare, for example, an arraylist like:

List list = new ArrayList(100);

This principle is used when we declare a Strategy object in the Context and then we instantiate as instance of a ConcreteStrategy that implements Strategy.

Ultimately, as said before, it is something to know, which can be really useful in many situations.

 
 
Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.

 
 
 

Related Posts

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Cross cultural challenges in web design, an overview

The user experience design of a product essentially lies between the intentions of the product and the characteristics of your user. - David Kadavy - The task of building a culturally appropriate…

A Java approach: While loop

Hello everyone and welcome back! After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called…

The easiest way to align items using flexbox

With the release of flexbox in CSS, it has become an essential tool when placing elements next to each other, since, by default, the children of a display: flexare stacked…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration