Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

A simple demonstration of Strategy Design Pattern in Java through a program

Introduction: 
So what is a Strategy Design Pattern in Java ?
A Strategy Design Pattern is a simple design pattern in java which provide us the design in which a particular piece of code behaves differently depending on the argument that we pass, is called as Strategy design pattern. Generally, there is a fixed part of the algorithm that is executed but varies with the type of strategy passed. In below example Shape object is the strategy that takes three different strategies and based on that gets us the urls of different shape.





Video tutorial to demonstrate, how to implement Strategy Design Pattern in Java.








Click here to download source code







Program to demonstrate Strategy Design Pattern in Java through a program

package strategy;

class Shape
{
   public String name()
   {
    return getClass().getSimpleName();
   } 
   
   public String getShapeUrl(String defaultUrl)
   {
    return defaultUrl + "/";
   }
}

class Triangle extends Shape
{
   public String getShapeUrl(String defaultUrl)
   {
      return defaultUrl + "/triangle.jpg";
   }
}

class Circle extends Shape
{
   public String getShapeUrl(String defaultUrl)
   {
      return defaultUrl + "/circle.jpg";
   }
}

class Square extends Shape
{
   public String getShapeUrl(String defaultUrl)
   {
      return defaultUrl + "/square.jpg";
   }
}

public class Strategy {

   public static void getShapeUrl(Shape s , String defaultUrl)
   {
      System.out.println("Getting the Url of image : " + s.name());
      System.out.println(s.getShapeUrl(defaultUrl));
   }
 
   public static String defaultUrl = "/shape/image";
 
   public static void main(String[] args) {
  
      getShapeUrl(new Triangle(), defaultUrl);
      getShapeUrl(new Circle(), defaultUrl);
      getShapeUrl(new Square(), defaultUrl);

   }

}




Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot