Strategy Design Pattern in Java

Spread the love

It is a pattern in which we have a group of algorithms or you can say group of functionalities for a particular task. At run time, client tells which algorithm or functionality we should invoke for that task.

One of the best example of strategy pattern is Collections.sort() method that takes a Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways.

Let’s implement an example in which we will implement the strategy pattern. It is a coffee vending machine. Client can order a Espresso Coffee or a Cappucino Coffee.

interface Coffee{
   void prepCoffee();
}

public class EspressoCoffee implements Coffee{

  public void prepCoffee(){
     System.out.println("Preparing Espresso Coffee");
  }

}

public class CappucinoCoffee implements Coffee{

  public void prepCoffee(){
     System.out.println("Preparing Cappucino Coffee");
  }

}

So here we have the 2 types of Coffee which implement the Coffee interface and implement the prepCoffee method which would prepare the respective coffee as per the client request.

Now let’s implement CoffeeVendingService Class.

public class CoffeeVendingService{
   
      public void execCoffeeOrder(Coffee c){
         c.prepCoffee();
      }
}

The service class would take the order and process it.

Now let’s implement the final client class through we place the order.

public class PlaceCoffeeOrder{

    public static void main(String[] args) {
        System.out.println("Take and process Coffee Orders");

        CoffeeVendingService cs = new CoffeeVendingService();
       
        //Client Placed order for Espresso Coffee
        cs.execCoffeeOrder(new EspressoCoffee());

        //Client Placed order for Cappucino Coffee
        cs.execCoffeeOrder(new CappucinoCoffee());
    }

}

So according to the request from the client, the respective coffee is prepared.

This is how strategy pattern works.