SlideShare a Scribd company logo
1 of 15
Strategy Pattern
(A Behavioral Pattern)
Behavioral Pattern
 concerned with algorithms and the assignment of responsibilities
  between objects

 describe not just patterns of objects or classes but also the patterns of
  communication between them.

 characterize complex control flow that's difficult to follow at run-time.

 shift your focus away from flow of control to let you concentrate just on
  the way objects are interconnected.

 Behavioral class patterns use inheritance to distribute behavior
  between classes.

 Behavioral object patterns use object composition rather than
  inheritance.
Strategy
 Intent
   Define a family of algorithms,
   encapsulate each one, and make them
   interchangeable. Strategy lets the
   algorithm vary independently from
   clients that use it.

 Also Known As
   Policy
Motivation
 There are a number of cases in programs where we’d like to do the same
 thing in several different ways.

       Save files in different formats.
     Compress files using different algorithms
     Capture video data using different compression schemes.
     Use different line-breaking strategies to display text data.
     Plot the same data in different formats: line graph, bar chart, or pie chart.


 We can avoid these problems by defining classes that encapsulate different algorithms.
  An algorithm that's encapsulated in this way is called a strategy.

 A Composition maintains a reference to a Compositor object. Whenever a Composition
  reformats its text, it forwards this responsibility to its Compositor object. The client of
  Composition specifies which Compositor should be used by installing the Compositor it
  desires into the Composition.
Motivation
 Suppose a Composition class is responsible for maintaining and updating the linebreaks
  of text displayed in a text viewer. Linebreaking strategies aren't implemented by the class
  Composition. Instead, they are implemented separately by subclasses of the abstract
  Compositor class. Compositor subclasses implement different strategies:

 SimpleCompositor implements a simple strategy that determines linebreaks one at a
  time.
 TeXCompositor implements the TeX algorithm for finding linebreaks. This strategy
  tries to optimize linebreaks globally, that is, one paragraph at a time.
 ArrayCompositor implements a strategy that selects breaks so that each row has a fixed
  number of items. It's useful for breaking a collection of icons into rows, for example.
Applicability
 Use the Strategy pattern when

    many related classes differ only in their behavior. Strategies provide a way to
      configure a class with one of many behaviors.

    you need different variants of an algorithm. For example, you might define
      algorithms reflecting different space/time trade-offs. Strategies can be used
      when these variants are implemented as a class hierarchy of algorithms [HO87].

    an algorithm uses data that clients shouldn't know about. Use the Strategy
      pattern to avoid exposing complex, algorithm-specific data structures.

    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.
Structure
Participants
 Strategy (Compositor)
    declares an interface common to all supported
     algorithms. Context uses this interface to call the
     algorithm defined by a ConcreteStrategy.
 ConcreteStrategy (SimpleCompositor,
  TeXCompositor, ArrayCompositor)
    implements the algorithm using the Strategy interface.
 Context (Composition)
    is configured with a ConcreteStrategy object.
    maintains a reference to a Strategy object.
    may define an interface that lets Strategy access its data.
Collaborations
 Strategy and Context interact to implement the chosen
  algorithm. A context may pass all data required by the
  algorithm to the strategy when the algorithm is called.
  Alternatively, the context can pass itself as an argument to
  Strategy operations. That lets the strategy call back on the
  context as required.

 A context forwards requests from its clients to its strategy.
  Clients usually create and pass a ConcreteStrategy object to
  the context; thereafter, clients interact with the context
  exclusively. There is often a family of ConcreteStrategy
  classes for a client to choose from.
Consequences
 Families of related algorithms.
 An alternative to subclassing
 Strategies eliminate conditional statements.
 A choice of implementations.
 Clients must be aware of different Strategies.
 Communication overhead between Strategy and
  Context.
 Increased number of objects.
Implementation
 Defining the Strategy and Context interfaces.


 Strategies as template parameters.


 Making Strategy objects optional.
Sample Code
Sample Code
Sample Code
Assignment
 Let’s consider a simplified graphing program that
  can present data as a line graph or a bar chart. The
  program should be extensible in future with type
  of charts.

More Related Content

What's hot (9)

WEKA: Practical Machine Learning Tools And Techniques
WEKA: Practical Machine Learning Tools And TechniquesWEKA: Practical Machine Learning Tools And Techniques
WEKA: Practical Machine Learning Tools And Techniques
 
Preparing Data
Preparing DataPreparing Data
Preparing Data
 
Report
ReportReport
Report
 
Textmining Predictive Models
Textmining Predictive ModelsTextmining Predictive Models
Textmining Predictive Models
 
Tensor decompositions for medical analytics
Tensor decompositions for medical analyticsTensor decompositions for medical analytics
Tensor decompositions for medical analytics
 
StackAdapt Machine Learning Pipeline
StackAdapt Machine Learning PipelineStackAdapt Machine Learning Pipeline
StackAdapt Machine Learning Pipeline
 
WEKA: Data Mining Input Concepts Instances And Attributes
WEKA: Data Mining Input Concepts Instances And AttributesWEKA: Data Mining Input Concepts Instances And Attributes
WEKA: Data Mining Input Concepts Instances And Attributes
 
Competition16
Competition16Competition16
Competition16
 
XL-MINER:Prediction
XL-MINER:PredictionXL-MINER:Prediction
XL-MINER:Prediction
 

Similar to Design patterns

Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagram
Sadhana28
 
Strategy
StrategyStrategy
Strategy
Monjurul Habib
 
ArchitectureOfAOMsWICSA3
ArchitectureOfAOMsWICSA3ArchitectureOfAOMsWICSA3
ArchitectureOfAOMsWICSA3
Erdem Sahin
 
UML Design Class Diagrams (2014)
UML Design Class Diagrams (2014)UML Design Class Diagrams (2014)
UML Design Class Diagrams (2014)
Miriam Ruiz
 

Similar to Design patterns (20)

UML-Advanced Software Engineering
UML-Advanced Software EngineeringUML-Advanced Software Engineering
UML-Advanced Software Engineering
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagram
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Nina Grantcharova - Approach to Separation of Concerns via Design Patterns
Nina Grantcharova - Approach to Separation of Concerns via Design PatternsNina Grantcharova - Approach to Separation of Concerns via Design Patterns
Nina Grantcharova - Approach to Separation of Concerns via Design Patterns
 
ap assignmnet presentation.pptx
ap assignmnet presentation.pptxap assignmnet presentation.pptx
ap assignmnet presentation.pptx
 
Strategy
StrategyStrategy
Strategy
 
Design Pattern (Strategy & Template)
Design Pattern (Strategy & Template)Design Pattern (Strategy & Template)
Design Pattern (Strategy & Template)
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
 
Architecture and design
Architecture and designArchitecture and design
Architecture and design
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Oomd unit1
Oomd unit1Oomd unit1
Oomd unit1
 
Behavioral design patterns presentation
Behavioral design patterns presentationBehavioral design patterns presentation
Behavioral design patterns presentation
 
ArchitectureOfAOMsWICSA3
ArchitectureOfAOMsWICSA3ArchitectureOfAOMsWICSA3
ArchitectureOfAOMsWICSA3
 
Sda 9
Sda   9Sda   9
Sda 9
 
chapter 5 Objectdesign.ppt
chapter 5 Objectdesign.pptchapter 5 Objectdesign.ppt
chapter 5 Objectdesign.ppt
 
UML Design Class Diagrams (2014)
UML Design Class Diagrams (2014)UML Design Class Diagrams (2014)
UML Design Class Diagrams (2014)
 
OOM Unit I - III.pdf
OOM Unit I - III.pdfOOM Unit I - III.pdf
OOM Unit I - III.pdf
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Design patterns

  • 2. Behavioral Pattern  concerned with algorithms and the assignment of responsibilities between objects  describe not just patterns of objects or classes but also the patterns of communication between them.  characterize complex control flow that's difficult to follow at run-time.  shift your focus away from flow of control to let you concentrate just on the way objects are interconnected.  Behavioral class patterns use inheritance to distribute behavior between classes.  Behavioral object patterns use object composition rather than inheritance.
  • 3. Strategy  Intent  Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.  Also Known As  Policy
  • 4. Motivation  There are a number of cases in programs where we’d like to do the same  thing in several different ways.  Save files in different formats.  Compress files using different algorithms  Capture video data using different compression schemes.  Use different line-breaking strategies to display text data.  Plot the same data in different formats: line graph, bar chart, or pie chart.  We can avoid these problems by defining classes that encapsulate different algorithms. An algorithm that's encapsulated in this way is called a strategy.  A Composition maintains a reference to a Compositor object. Whenever a Composition reformats its text, it forwards this responsibility to its Compositor object. The client of Composition specifies which Compositor should be used by installing the Compositor it desires into the Composition.
  • 5. Motivation  Suppose a Composition class is responsible for maintaining and updating the linebreaks of text displayed in a text viewer. Linebreaking strategies aren't implemented by the class Composition. Instead, they are implemented separately by subclasses of the abstract Compositor class. Compositor subclasses implement different strategies:  SimpleCompositor implements a simple strategy that determines linebreaks one at a time.  TeXCompositor implements the TeX algorithm for finding linebreaks. This strategy tries to optimize linebreaks globally, that is, one paragraph at a time.  ArrayCompositor implements a strategy that selects breaks so that each row has a fixed number of items. It's useful for breaking a collection of icons into rows, for example.
  • 6. Applicability  Use the Strategy pattern when  many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.  you need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms [HO87].  an algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.  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.
  • 8. Participants  Strategy (Compositor)  declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.  ConcreteStrategy (SimpleCompositor, TeXCompositor, ArrayCompositor)  implements the algorithm using the Strategy interface.  Context (Composition)  is configured with a ConcreteStrategy object.  maintains a reference to a Strategy object.  may define an interface that lets Strategy access its data.
  • 9. Collaborations  Strategy and Context interact to implement the chosen algorithm. A context may pass all data required by the algorithm to the strategy when the algorithm is called. Alternatively, the context can pass itself as an argument to Strategy operations. That lets the strategy call back on the context as required.  A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively. There is often a family of ConcreteStrategy classes for a client to choose from.
  • 10. Consequences  Families of related algorithms.  An alternative to subclassing  Strategies eliminate conditional statements.  A choice of implementations.  Clients must be aware of different Strategies.  Communication overhead between Strategy and Context.  Increased number of objects.
  • 11. Implementation  Defining the Strategy and Context interfaces.  Strategies as template parameters.  Making Strategy objects optional.
  • 15. Assignment  Let’s consider a simplified graphing program that can present data as a line graph or a bar chart. The program should be extensible in future with type of charts.