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

                                       Code Reuse
                            Easy
                         Maintenance

               Easy
             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


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




             Concrete         Concrete               Concrete
             Strategy1        Strategy2             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

                                      Code Reuse
                           Easy
                        Maintenance

              Easy
            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               Context


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




                    Concrete            Concrete               Concrete
                    Strategy1           Strategy2             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




References
  http://paginas.fe.up.pt/~aaguiar/as/gof/hires/pat5i.htm

  http://www.oodesign.com/strategy-pattern.html
Slide 25




Thank You!

More Related Content

What's hot

Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
Herman Peeren
 
Swing
SwingSwing
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Exception handling
Exception handlingException handling
Exception handling
Anna Pietras
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
Krazy Koder
 
POO - 20 - Wrapper Classes
POO - 20 - Wrapper ClassesPOO - 20 - Wrapper Classes
POO - 20 - Wrapper Classes
Ludimila Monjardim Casagrande
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
Shakil Ahmed
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
Edureka!
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Edureka!
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
Victor Rentea
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
NexThoughts Technologies
 
NestJS
NestJSNestJS
NestJS
Wilson Su
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Core java
Core javaCore java
Core java
Shivaraj R
 

What's hot (20)

Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Swing
SwingSwing
Swing
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Exception handling
Exception handlingException handling
Exception handling
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
 
POO - 20 - Wrapper Classes
POO - 20 - Wrapper ClassesPOO - 20 - Wrapper Classes
POO - 20 - Wrapper Classes
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
NestJS
NestJSNestJS
NestJS
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Core java
Core javaCore java
Core java
 

Similar to Strategy Design Pattern

Strategy design pattern
Strategy design pattern Strategy design pattern
Strategy design pattern
aswapnal
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
First Tuesday Bergen
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
First Tuesday Bergen
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
gauravavam
 
Google GIN
Google GINGoogle GIN
Google GIN
Anh Quân
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
Anh Quân
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
Clare Macrae
 
Exploring CameraX from JetPack
Exploring CameraX from JetPackExploring CameraX from JetPack
Exploring CameraX from JetPack
Hassan Abid
 
Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
Katy Slemon
 
The real beginner's guide to android testing
The real beginner's guide to android testingThe real beginner's guide to android testing
The real beginner's guide to android testing
Eric (Trung Dung) Nguyen
 
Qt for beginners part 4 doing more
Qt for beginners part 4   doing moreQt for beginners part 4   doing more
Qt for beginners part 4 doing more
ICS
 
Design Patterns
Design PatternsDesign Patterns
Guide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in KotlinGuide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in Kotlin
RapidValue
 
Factory method & strategy pattern
Factory method & strategy patternFactory method & strategy pattern
Factory method & strategy pattern
babak danyal
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
laxmi.katkar
 
RL2 Dot Brighton
RL2 Dot BrightonRL2 Dot Brighton
RL2 Dot Brighton
Shaun Smith
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
ssuser9a23691
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
Sami Mut
 
cscript_controller.pdf
cscript_controller.pdfcscript_controller.pdf
cscript_controller.pdf
VcTrn1
 

Similar to Strategy Design Pattern (20)

Strategy design pattern
Strategy design pattern Strategy design pattern
Strategy design pattern
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Google GIN
Google GINGoogle GIN
Google GIN
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
 
Exploring CameraX from JetPack
Exploring CameraX from JetPackExploring CameraX from JetPack
Exploring CameraX from JetPack
 
Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
 
The real beginner's guide to android testing
The real beginner's guide to android testingThe real beginner's guide to android testing
The real beginner's guide to android testing
 
Qt for beginners part 4 doing more
Qt for beginners part 4   doing moreQt for beginners part 4   doing more
Qt for beginners part 4 doing more
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Guide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in KotlinGuide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in Kotlin
 
Factory method & strategy pattern
Factory method & strategy patternFactory method & strategy pattern
Factory method & strategy pattern
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
RL2 Dot Brighton
RL2 Dot BrightonRL2 Dot Brighton
RL2 Dot Brighton
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
 
cscript_controller.pdf
cscript_controller.pdfcscript_controller.pdf
cscript_controller.pdf
 

Recently uploaded

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 

Recently uploaded (20)

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 

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 Code Reuse Easy Maintenance Easy 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 <<interface>> IComputeStrategy ----------------------- Operation() Concrete Concrete Concrete Strategy1 Strategy2 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 Code Reuse Easy Maintenance Easy 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 Context <<interface>> IComputeStrategy ----------------------- Operation() Concrete Concrete Concrete Strategy1 Strategy2 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.
  • 24. Slide 24 References  http://paginas.fe.up.pt/~aaguiar/as/gof/hires/pat5i.htm  http://www.oodesign.com/strategy-pattern.html

Editor's Notes

  1. Project Name
  2. Project Name
  3. Project Name