SlideShare a Scribd company logo
Slide 1




Java Design Pattern
Strategy Pattern


                   Swapnal Agrawal
                   Module Lead

                   Ganesh Kolhe
                   Senior Team Lead
Slide 2




Outline
 Overview
 Analysis and Design
 Module and Client Implementation
 Strategy
 Variation in the Implementation
 Java API Usage
 Consequences
Slide 3




Overview
 Using different algorithms on some values such as sorting, filters,
  etc.


 Applying some logic or calculation to return a value to the client.


 Implementing the algorithms in such a way that the correct
  algorithm is provided from different available algorithms on the
  client's request and the required value to the client is returned.
Slide 4




Analysis and Design
 There are many solutions and alternatives which seem to be very
  simple and straightforward. Following are two such examples:


    Separate implementation logic from
      client code.


    Create a static class with a method
      and if-else or switch case ladder can
      be used to fetch different algorithms.
Slide 5




Module Implementation
public final class Compute {
       public static final int COMPUTE_SUM= 1;
       public static final int COMPUTE_PRODUCT= 2;

      private Compute() {}

       public static double getComputedValue(int type, double
a , double b){
              if (type == COMPUTE_SUM){
                     return a + b;
              }else if (type == COMPUTE_PRODUCT){
                     return a * b;
              }
              throw new IllegalArgumentException();
       }
}
Slide 6




Client Implementation
public class ApplicationClient {
      public static void main(String[] args) {
             System.out.println("Sum = "+
                   Compute.getComputedValue(
                   Compute.COMPUTE_SUM, 20, 25));


             System.out.println("Product = "+
                   Compute.getComputedValue(
                   Compute.COMPUTE_PRODUCT, 7, 3));
      }
}
Slide 7




The Design



             Easy Testing
              Easy Testing

                                        Code Reuse
                                         Code Reuse
                             Easy
                              Easy
                          Maintenance
                          Maintenance

                Easy
                 Easy
             Expansion
              Expansion
Slide 8




The Strategy
Design Pattern Type: Behavioral
Idea: Algorithm
Alias: Policy

A class defines many behaviors and these appear as multiple conditional
statements in its operations. Instead of many conditionals, move related
conditional branches into their own Strategy class.
Strategy pattern defines family of algorithms, encapsulates each one, and
makes them interchangeable.
 Strategy lets algorithms vary independently from clients that use them.
   Calculations are based on the clients’ abstraction (not using the clients’
   implementation or global data).
Slide 9




Strategy Implementation
 Define a Strategy Interface that is common to all supported
   algorithms.


 Strategy Interface defines your Strategy Object’s behavior.


 Implement the Concrete Strategy classes that share the common
   Strategy interface.
Slide 10




The Class Diagram

    Client
     Client


                               <<interface>>
                                <<interface>>
                           IComputeStrategy
                             IComputeStrategy
                            -----------------------
                              -----------------------
                                 Operation()
                                  Operation()




              Concrete
               Concrete         Concrete
                                 Concrete                Concrete
                                                          Concrete
              Strategy1
               Strategy1        Strategy2
                                 Strategy2              Strategy…n
                                                         Strategy…n
Slide 11




Module Implementation By Using Strategy
public interface IComputeStrategy01 {
       public double getValue(double a, double b);
}

public class ComputeSum01 implements IComputeStrategy01 {
       public double getValue(double a, double b) {
              return a + b;
       }
}

public class ComputeProduct01 implements IComputeStrategy01 {
       public double getValue(double a, double b) {
              return a * b;
       }
}
Slide 12




Client Code Using the Implementation
public class StrategyApplicationClient01 {
       public static void main(String[] args) {

      IComputeStrategy01 compute1 = new ComputeSum01();
      System.out.println("Sum = "+
             compute1.getValue(20, 25));

      IComputeStrategy01 compute2 = new ComputeProduct02();
      System.out.println("Product = "+
             compute2.getValue(7, 3));
      }
}
Slide 13




The Strategy Design



            Easy Testing
             Easy Testing

                                       Code Reuse
                                        Code Reuse
                            Easy
                             Easy
                         Maintenance
                         Maintenance

               Easy
                Easy
            Expansion
             Expansion
Slide 14




Variation In The Implementation
 Singleton:

    Concrete classes as singleton objects.


    Define a static method to get a singleton instance.
Slide 15




Strategy Implementation By Using Singleton
//singleton implementation
public final class ComputeSum02 implements IComputeStrategy02
{

private static ComputeSum02 computeSum = new ComputeSum02();

private ComputeSum02(){}

public static IComputeStrategy02 getOnlyOneInstance(){
return computeSum;
}

public double getValue(double a, double b) {
return a + b;
}
}
Slide 16




Client - Strategy Implementation By Using Singleton
public class StrategyApplicationClient02 {
       public static void main(String[] args) {

             IComputeStrategy02 compute1 =
                    ComputeSum02.getOnlyOneInstance();
             System.out.println("Sum = "+
                    compute1.getValue(20, 25));

             IComputeStrategy02 compute2 =
                     ComputeProduct02.getOnlyOneInstance();
             System.out.println(“Product= "+
                    compute2.getValue(7, 3));
      }
}
Slide 17




Another Variation In the Implementation
Context:
   is configured with a Concrete Strategy object.

   maintains a private reference to a Strategy object.
   may define an interface that lets Strategy access its data.



  By changing the Context's Strategy, different behaviors can be
     obtained.
Slide 18




Strategy Implementation By Using Context
public interface IComputeStrategy03 {
        public double getValue(double a, double b);
}
//strategy context implementation
public class StrategyContext03 {
        private IComputeStrategy03 computeStrategy;
        public StrategyContext03 (IComputeStrategy03 computeStrategy){
                this.computeStrategy = computeStrategy;
        }
        public void setComputeStrategy(IComputeStrategy03
computeStrategy){
                this.computeStrategy = computeStrategy;
        }
        public double executeComputeStrategy(double a , double b){
                return computeStrategy.getValue(a, b);
        }
}
Slide 19




Client - Strategy Implementation By Using Context
public class StrategyApplicationClient03 {
 public static void main(String[] args) {

      StrategyContext03 ctx = new StrategyContext03(
             ComputeSum03.getOnlyOneInstance());
      System.out.println("Sum = "+
             ctx.executeComputeStrategy(20, 25));

      ctx.setComputeStratey(
             ComputeProduct03.getOnlyOneInstance());
      System.out.println("Product = "+
      ctx.executeComputeStrategy(7, 3));
      }
}
Slide 20




The Class Diagram

    Client
     Client              Context
                          Context


                                       <<interface>>
                                        <<interface>>
                                    IComputeStrategy
                                     IComputeStrategy
                                     -----------------------
                                      -----------------------
                                         Operation()
                                          Operation()




                    Concrete
                     Concrete            Concrete
                                          Concrete               Concrete
                                                                  Concrete
                    Strategy1
                     Strategy1           Strategy2
                                          Strategy2             Strategy…n
                                                                 Strategy…n
Slide 21




Java API Usage

                                 checkInputStream and checkOutputStream uses the
Java.util.zip
                                 strategy pattern to compute checksums on byte stream.


                                 compare(), executed by among
Java.util.comparator
                                 others Collections#sort().


                                 the service() and all doXXX() methods take
                                 HttpServletRequest and HttpServletResponse and the
Javax.servlet.http.HttpServlet
                                 implementor has to process them (and not to get hold
                                 of them as instance variables!).
Slide 22




Consequences
 Benefits
   Provides an alternative to sub classing the Context class to get a variety
    of algorithms or behaviors.
   Eliminates large conditional statements.

   Provides a choice of implementations for the same behavior.



 Shortcomings
   Increases the number of objects.

   All algorithms must use the same Strategy interface.



  Think twice before implementing the Strategy pattern or any other design
     pattern to match your requirements.
Slide 23




About Cross Country Infotech
Cross Country Infotech (CCI) Pvt. Ltd. is a part of the Cross Country Healthcare (NYSE:
CCRN) group of companies. CCI specializes in providing a gamut of IT/ITES services and
is well equipped with technical expertise to provide smarter solutions to its customers.
Some of our cutting-edge technology offerings include Mobile, Web and BI Application
Development; ECM and Informix 4GL Solutions; and Technical Documentation, UI
Design and Testing services.
Slide 24




Thank You!

More Related Content

Similar to Strategy design pattern (20)

PPT
Strategy Design Pattern
Ganesh Kolhe
 
PDF
Model driven development using smart use cases and domain driven design
Sander Hoogendoorn
 
PPTX
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Steven Smith
 
PPTX
Developer Friendly API Design
theamiableapi
 
PDF
20090410 J Spring Pragmatic Model Driven Development In Java Using Smart
Sander Hoogendoorn
 
PPTX
Software System Architecture-Lecture 6.pptx
ssuser9a23691
 
PDF
Simple Pure Java
Anton Keks
 
PDF
Design Patterns
adil raja
 
PPTX
Strategy Pattern
Shahriar Iqbal Chowdhury
 
PPTX
Strategy
Monjurul Habib
 
PDF
Key points of good software programming
Marcio Luis da Silva
 
PPTX
L06 Using Design Patterns
Ólafur Andri Ragnarsson
 
PPT
Estimation and planning with smart use cases
Robert de Wolff
 
DOC
Student copybca sem3-se
anilmanu2001
 
PDF
Java beginners meetup: Introduction to class and application design
Patrick Kostjens
 
PPTX
Software Development: Beyond Training wheels
Naveenkumar Muguda
 
PPTX
Designing DDD Aggregates
Andrew McCaughan
 
PDF
Aggregates, Entities and Value objects - Devnology 2010 community day
Rick van der Arend
 
PDF
Introducing MDSD
Pedro J. Molina
 
PDF
Lição prova professor coordenador
Paulo Gandra de Sousa
 
Strategy Design Pattern
Ganesh Kolhe
 
Model driven development using smart use cases and domain driven design
Sander Hoogendoorn
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Steven Smith
 
Developer Friendly API Design
theamiableapi
 
20090410 J Spring Pragmatic Model Driven Development In Java Using Smart
Sander Hoogendoorn
 
Software System Architecture-Lecture 6.pptx
ssuser9a23691
 
Simple Pure Java
Anton Keks
 
Design Patterns
adil raja
 
Strategy Pattern
Shahriar Iqbal Chowdhury
 
Strategy
Monjurul Habib
 
Key points of good software programming
Marcio Luis da Silva
 
L06 Using Design Patterns
Ólafur Andri Ragnarsson
 
Estimation and planning with smart use cases
Robert de Wolff
 
Student copybca sem3-se
anilmanu2001
 
Java beginners meetup: Introduction to class and application design
Patrick Kostjens
 
Software Development: Beyond Training wheels
Naveenkumar Muguda
 
Designing DDD Aggregates
Andrew McCaughan
 
Aggregates, Entities and Value objects - Devnology 2010 community day
Rick van der Arend
 
Introducing MDSD
Pedro J. Molina
 
Lição prova professor coordenador
Paulo Gandra de Sousa
 

Recently uploaded (20)

PPTX
Design & Thinking for Engineering graduates
NEELAMRAWAT48
 
DOCX
BusinessPlan_redesignedf word format .docx
MohammadMaqatif
 
PPTX
Morph Slide Presentation transition.pptx
ArifaAkter10
 
PPTX
3. Introduction to Materials and springs.pptx
YESIMSMART
 
PPTX
Style and aesthetic about fashion lifestyle
Khushi Bera
 
PDF
5 Psychological Principles to Apply in Web Design for Better User Engagement
DigitalConsulting
 
PPTX
Dasar Dasar Desain Grafis Dasar Dasar Desain Grafis.pptx
muhamad149
 
PPT
Strengthening of an existing reinforced concrete structure.ppt
erdarshanpshah
 
PDF
Fashion Design Portfolio Berta Villanueva
BertaVillanueva
 
PDF
Ggggggggggggggggggggroup singing.pdf.pdf
nadifalrazi3
 
PDF
mlbrolllist2024-25 (1)ygrude4ferfssrddde
rishabh1chaurasia4
 
PDF
Shayna Andrieze Yjasmin Goles - Your VA!
shaynagoles31
 
PDF
Zidane ben hmida _ Portfolio
Zidane Ben Hmida
 
PPTX
Engagement for marriage life ethics b.pptx
SyedBabar19
 
PPTX
Digital Printing presentation-update-26.08.24.pptx
MDFoysalAhmed13
 
PPTX
DISS-Group-5_110345.pptx Basic Concepts of the major social science
mattygido
 
PDF
Dunes.pdf, Durable and Seamless Solid Surface Countertops
tranquil01
 
PDF
Spring Summer 2027 Beauty & Wellness Trend Book
Peclers Paris
 
PDF
Hossain Kamyab on Mixing and Matching Furniture.pdf
Hossain Kamyab
 
PPTX
confluence of tradition in modernity- design approaches and design thinking
madhuvidya7
 
Design & Thinking for Engineering graduates
NEELAMRAWAT48
 
BusinessPlan_redesignedf word format .docx
MohammadMaqatif
 
Morph Slide Presentation transition.pptx
ArifaAkter10
 
3. Introduction to Materials and springs.pptx
YESIMSMART
 
Style and aesthetic about fashion lifestyle
Khushi Bera
 
5 Psychological Principles to Apply in Web Design for Better User Engagement
DigitalConsulting
 
Dasar Dasar Desain Grafis Dasar Dasar Desain Grafis.pptx
muhamad149
 
Strengthening of an existing reinforced concrete structure.ppt
erdarshanpshah
 
Fashion Design Portfolio Berta Villanueva
BertaVillanueva
 
Ggggggggggggggggggggroup singing.pdf.pdf
nadifalrazi3
 
mlbrolllist2024-25 (1)ygrude4ferfssrddde
rishabh1chaurasia4
 
Shayna Andrieze Yjasmin Goles - Your VA!
shaynagoles31
 
Zidane ben hmida _ Portfolio
Zidane Ben Hmida
 
Engagement for marriage life ethics b.pptx
SyedBabar19
 
Digital Printing presentation-update-26.08.24.pptx
MDFoysalAhmed13
 
DISS-Group-5_110345.pptx Basic Concepts of the major social science
mattygido
 
Dunes.pdf, Durable and Seamless Solid Surface Countertops
tranquil01
 
Spring Summer 2027 Beauty & Wellness Trend Book
Peclers Paris
 
Hossain Kamyab on Mixing and Matching Furniture.pdf
Hossain Kamyab
 
confluence of tradition in modernity- design approaches and design thinking
madhuvidya7
 
Ad

Strategy design pattern

  • 1. Slide 1 Java Design Pattern Strategy Pattern Swapnal Agrawal Module Lead Ganesh Kolhe Senior Team Lead
  • 2. Slide 2 Outline  Overview  Analysis and Design  Module and Client Implementation  Strategy  Variation in the Implementation  Java API Usage  Consequences
  • 3. Slide 3 Overview  Using different algorithms on some values such as sorting, filters, etc.  Applying some logic or calculation to return a value to the client.  Implementing the algorithms in such a way that the correct algorithm is provided from different available algorithms on the client's request and the required value to the client is returned.
  • 4. Slide 4 Analysis and Design  There are many solutions and alternatives which seem to be very simple and straightforward. Following are two such examples:  Separate implementation logic from client code.  Create a static class with a method and if-else or switch case ladder can be used to fetch different algorithms.
  • 5. Slide 5 Module Implementation public final class Compute { public static final int COMPUTE_SUM= 1; public static final int COMPUTE_PRODUCT= 2; private Compute() {} public static double getComputedValue(int type, double a , double b){ if (type == COMPUTE_SUM){ return a + b; }else if (type == COMPUTE_PRODUCT){ return a * b; } throw new IllegalArgumentException(); } }
  • 6. Slide 6 Client Implementation public class ApplicationClient { public static void main(String[] args) { System.out.println("Sum = "+ Compute.getComputedValue( Compute.COMPUTE_SUM, 20, 25)); System.out.println("Product = "+ Compute.getComputedValue( Compute.COMPUTE_PRODUCT, 7, 3)); } }
  • 7. Slide 7 The Design Easy Testing Easy Testing Code Reuse Code Reuse Easy Easy Maintenance Maintenance Easy Easy Expansion Expansion
  • 8. Slide 8 The Strategy Design Pattern Type: Behavioral Idea: Algorithm Alias: Policy A class defines many behaviors and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class. Strategy pattern defines family of algorithms, encapsulates each one, and makes them interchangeable.  Strategy lets algorithms vary independently from clients that use them. Calculations are based on the clients’ abstraction (not using the clients’ implementation or global data).
  • 9. Slide 9 Strategy Implementation  Define a Strategy Interface that is common to all supported algorithms.  Strategy Interface defines your Strategy Object’s behavior.  Implement the Concrete Strategy classes that share the common Strategy interface.
  • 10. Slide 10 The Class Diagram Client Client <<interface>> <<interface>> IComputeStrategy IComputeStrategy ----------------------- ----------------------- Operation() Operation() Concrete Concrete Concrete Concrete Concrete Concrete Strategy1 Strategy1 Strategy2 Strategy2 Strategy…n Strategy…n
  • 11. Slide 11 Module Implementation By Using Strategy public interface IComputeStrategy01 { public double getValue(double a, double b); } public class ComputeSum01 implements IComputeStrategy01 { public double getValue(double a, double b) { return a + b; } } public class ComputeProduct01 implements IComputeStrategy01 { public double getValue(double a, double b) { return a * b; } }
  • 12. Slide 12 Client Code Using the Implementation public class StrategyApplicationClient01 { public static void main(String[] args) { IComputeStrategy01 compute1 = new ComputeSum01(); System.out.println("Sum = "+ compute1.getValue(20, 25)); IComputeStrategy01 compute2 = new ComputeProduct02(); System.out.println("Product = "+ compute2.getValue(7, 3)); } }
  • 13. Slide 13 The Strategy Design Easy Testing Easy Testing Code Reuse Code Reuse Easy Easy Maintenance Maintenance Easy Easy Expansion Expansion
  • 14. Slide 14 Variation In The Implementation  Singleton:  Concrete classes as singleton objects.  Define a static method to get a singleton instance.
  • 15. Slide 15 Strategy Implementation By Using Singleton //singleton implementation public final class ComputeSum02 implements IComputeStrategy02 { private static ComputeSum02 computeSum = new ComputeSum02(); private ComputeSum02(){} public static IComputeStrategy02 getOnlyOneInstance(){ return computeSum; } public double getValue(double a, double b) { return a + b; } }
  • 16. Slide 16 Client - Strategy Implementation By Using Singleton public class StrategyApplicationClient02 { public static void main(String[] args) { IComputeStrategy02 compute1 = ComputeSum02.getOnlyOneInstance(); System.out.println("Sum = "+ compute1.getValue(20, 25)); IComputeStrategy02 compute2 = ComputeProduct02.getOnlyOneInstance(); System.out.println(“Product= "+ compute2.getValue(7, 3)); } }
  • 17. Slide 17 Another Variation In the Implementation Context:  is configured with a Concrete Strategy object.  maintains a private reference to a Strategy object.  may define an interface that lets Strategy access its data. By changing the Context's Strategy, different behaviors can be obtained.
  • 18. Slide 18 Strategy Implementation By Using Context public interface IComputeStrategy03 { public double getValue(double a, double b); } //strategy context implementation public class StrategyContext03 { private IComputeStrategy03 computeStrategy; public StrategyContext03 (IComputeStrategy03 computeStrategy){ this.computeStrategy = computeStrategy; } public void setComputeStrategy(IComputeStrategy03 computeStrategy){ this.computeStrategy = computeStrategy; } public double executeComputeStrategy(double a , double b){ return computeStrategy.getValue(a, b); } }
  • 19. Slide 19 Client - Strategy Implementation By Using Context public class StrategyApplicationClient03 { public static void main(String[] args) { StrategyContext03 ctx = new StrategyContext03( ComputeSum03.getOnlyOneInstance()); System.out.println("Sum = "+ ctx.executeComputeStrategy(20, 25)); ctx.setComputeStratey( ComputeProduct03.getOnlyOneInstance()); System.out.println("Product = "+ ctx.executeComputeStrategy(7, 3)); } }
  • 20. Slide 20 The Class Diagram Client Client Context Context <<interface>> <<interface>> IComputeStrategy IComputeStrategy ----------------------- ----------------------- Operation() Operation() Concrete Concrete Concrete Concrete Concrete Concrete Strategy1 Strategy1 Strategy2 Strategy2 Strategy…n Strategy…n
  • 21. Slide 21 Java API Usage checkInputStream and checkOutputStream uses the Java.util.zip strategy pattern to compute checksums on byte stream. compare(), executed by among Java.util.comparator others Collections#sort(). the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the Javax.servlet.http.HttpServlet implementor has to process them (and not to get hold of them as instance variables!).
  • 22. Slide 22 Consequences  Benefits  Provides an alternative to sub classing the Context class to get a variety of algorithms or behaviors.  Eliminates large conditional statements.  Provides a choice of implementations for the same behavior.  Shortcomings  Increases the number of objects.  All algorithms must use the same Strategy interface. Think twice before implementing the Strategy pattern or any other design pattern to match your requirements.
  • 23. Slide 23 About Cross Country Infotech Cross Country Infotech (CCI) Pvt. Ltd. is a part of the Cross Country Healthcare (NYSE: CCRN) group of companies. CCI specializes in providing a gamut of IT/ITES services and is well equipped with technical expertise to provide smarter solutions to its customers. Some of our cutting-edge technology offerings include Mobile, Web and BI Application Development; ECM and Informix 4GL Solutions; and Technical Documentation, UI Design and Testing services.

Editor's Notes