SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Stéphane Ducasse 1
Stéphane Ducasse
stephane.ducasse@inria.fr
http://stephane.ducasse.free.fr/
Strategy
S.Ducasse 2
Strategy
Define a family of algorithms,
encapsulate each in a separate
class and define each class with
the same interface so that they can
be interchangeable.
Also Know as Policy
S.Ducasse 3
Strategy Intent
Define a family of algorithms, encapsulate each in a
separate class and define each class with the same
interface so that they can be interchangeable.
S.Ducasse 4
Motivation
Many algorithms exist for breaking a stream into
lines. Hardwiring them into the classes that
requires them has the following problems:
Clients get more complex
Different algorithms can be used at different times
Difficult to add new algorithms at run-time
S.Ducasse 5
Code Smells
Composition>>repair
formatting == #Simple
ifTrue: [ self formatWihtSimpleAlgo]
ifFalse: [ formatting == #Tex
ifTrue: [self formatWithTex]
....]
S.Ducasse 6
Alternative
Composition>>repair
| selector |
selector := (‘formatWith, formatting) asSymbol.
self perform: selector
Still your class gets complex...
S.Ducasse 7
Inheritance?
May not be the solution since:
- you have to create objects of the right class
- it is difficult to change the policy at run-time
- you can get an explosion of classes bloated with
the use of a functionality and the functionalities.
- no clear identification of responsibility
S.Ducasse 8
Strategy Solution
S.Ducasse 9
When
Many related classes differ only in their behavior
You have variants of an algorithm (space/time)
An algorithm uses data that the clients does not
have to know
S.Ducasse 10
Structure
Composition>>repair
formatter format: self
S.Ducasse 11
Participants
Strategy (Compositor)
declares an interface common to all concrete strategies
Concrete Strategies
implement algorithm
Context
configure with concrete strategy
maintains a reference to the concrete strategy
may define an interface to let the strategy access data
S.Ducasse 12
Collaborations (i)
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
GraphVisualizer>>graphIt
....
grapher plot: data using: graphPane pen
Grapher>>plot: data using: aPen
S.Ducasse 13
Context passes itself as argument
Also know as self-delegation...
GraphVisualizer>>graphIt
grapher plotFor: self
BartChartGrapher>>plotFor: aGraphVisualizer
|data|
data := aGraphVisualizer data
....
S.Ducasse 14
BackPointer
Grapher class>>for: aGraphVisualizer
^ self new graphVisualizer: aGraphVisualizer
BartChartGrapher>>plot
...
graphVisualizer data..
graphVisualizer pen
Grapher (Strategy) points directly to GraphVisualizer
(Context), so sharing strategy between different context
may be difficult, if sharing is needed then use self-delegation
S.Ducasse 15
Collaboration (ii)
“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.“ GOF
Not sure that the client has to choose...
S.Ducasse 16
Consequences
Define a family of pluggable algorithms
Eliminates conditional statements
Clients can choose between several
implementations
Clients must be aware of the different strategies
Increase the number of objects
Communication overhead between client and
strategies
Weaken encapsulation of the client
S.Ducasse 17
Domain-Specific Objects as Strategies
Strategies do not have to be limited to one single
algorithm
They may represent domain specific knowledge
Mortgage
FixedRateMortgage
OneYear...
S.Ducasse 18
Known Uses
ImageRenderer inVW: “a technique to render an
image using a limited palette”
ImageRenderer
NearestPaint
OrderedDither
ErrorDiffusion
View-Controller
a view instance uses a controller object to handle
and respond to user input via mouse or keyboard.
Controllers can be changed at run-time

Weitere ähnliche Inhalte

Andere mochten auch (20)

15 - Streams
15 - Streams15 - Streams
15 - Streams
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
10 reflection
10 reflection10 reflection
10 reflection
 
Stoop 400-metaclass only
Stoop 400-metaclass onlyStoop 400-metaclass only
Stoop 400-metaclass only
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 
10 - OOP - Inheritance (b)
10 - OOP - Inheritance (b)10 - OOP - Inheritance (b)
10 - OOP - Inheritance (b)
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
 
Stoop 416-lsp
Stoop 416-lspStoop 416-lsp
Stoop 416-lsp
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop 303-advanced blocks
Stoop 303-advanced blocksStoop 303-advanced blocks
Stoop 303-advanced blocks
 
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
 
12 - Conditions and Loops
12 - Conditions and Loops12 - Conditions and Loops
12 - Conditions and Loops
 
Stoop 400 o-metaclassonly
Stoop 400 o-metaclassonlyStoop 400 o-metaclassonly
Stoop 400 o-metaclassonly
 

Ähnlich wie Stoop 436-strategy

Factory method & strategy pattern
Factory method & strategy patternFactory method & strategy pattern
Factory method & strategy patternbabak danyal
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat SheetLaura Hughes
 
Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programmingTim Essam
 
What's New in DITA 1.3
What's New in DITA 1.3What's New in DITA 1.3
What's New in DITA 1.3IXIASOFT
 
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...InfluxData
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsMichael Heron
 
Anything but simple Mathematica
Anything but simple MathematicaAnything but simple Mathematica
Anything but simple MathematicaSergeiPronkevich
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply FunctionSakthi Dasans
 
Mis presentation
Mis presentationMis presentation
Mis presentationprutha_beta
 
Design Pattern(decorator design pattern) and anti pattern
Design Pattern(decorator design pattern) and anti patternDesign Pattern(decorator design pattern) and anti pattern
Design Pattern(decorator design pattern) and anti patternArslan Ahmad
 
SICP_2.5 일반화된 연산시스템
SICP_2.5 일반화된 연산시스템SICP_2.5 일반화된 연산시스템
SICP_2.5 일반화된 연산시스템HyeonSeok Choi
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with RMartin Jung
 
Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...
Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...
Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...Edureka!
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsAndroid App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsDiego Grancini
 
Factory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesFactory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesbabak danyal
 

Ähnlich wie Stoop 436-strategy (20)

Factory method & strategy pattern
Factory method & strategy patternFactory method & strategy pattern
Factory method & strategy pattern
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
 
Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programming
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
What's New in DITA 1.3
What's New in DITA 1.3What's New in DITA 1.3
What's New in DITA 1.3
 
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
R studio
R studio R studio
R studio
 
Anything but simple Mathematica
Anything but simple MathematicaAnything but simple Mathematica
Anything but simple Mathematica
 
Design patterns
Design patternsDesign patterns
Design patterns
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
 
Mis presentation
Mis presentationMis presentation
Mis presentation
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
An Introduction to MATLAB with Worked Examples
An Introduction to MATLAB with Worked ExamplesAn Introduction to MATLAB with Worked Examples
An Introduction to MATLAB with Worked Examples
 
Design Pattern(decorator design pattern) and anti pattern
Design Pattern(decorator design pattern) and anti patternDesign Pattern(decorator design pattern) and anti pattern
Design Pattern(decorator design pattern) and anti pattern
 
SICP_2.5 일반화된 연산시스템
SICP_2.5 일반화된 연산시스템SICP_2.5 일반화된 연산시스템
SICP_2.5 일반화된 연산시스템
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with R
 
Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...
Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...
Introduction To TensorFlow | Deep Learning Using TensorFlow | TensorFlow Tuto...
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsAndroid App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
 
Factory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesFactory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilities
 

Mehr von The World of Smalltalk (16)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
06 debugging
06 debugging06 debugging
06 debugging
 
05 seaside
05 seaside05 seaside
05 seaside
 
04 idioms
04 idioms04 idioms
04 idioms
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
02 basics
02 basics02 basics
02 basics
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 

Kürzlich hochgeladen

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Kürzlich hochgeladen (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

Stoop 436-strategy

  • 1. Stéphane Ducasse 1 Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Strategy
  • 2. S.Ducasse 2 Strategy Define a family of algorithms, encapsulate each in a separate class and define each class with the same interface so that they can be interchangeable. Also Know as Policy
  • 3. S.Ducasse 3 Strategy Intent Define a family of algorithms, encapsulate each in a separate class and define each class with the same interface so that they can be interchangeable.
  • 4. S.Ducasse 4 Motivation Many algorithms exist for breaking a stream into lines. Hardwiring them into the classes that requires them has the following problems: Clients get more complex Different algorithms can be used at different times Difficult to add new algorithms at run-time
  • 5. S.Ducasse 5 Code Smells Composition>>repair formatting == #Simple ifTrue: [ self formatWihtSimpleAlgo] ifFalse: [ formatting == #Tex ifTrue: [self formatWithTex] ....]
  • 6. S.Ducasse 6 Alternative Composition>>repair | selector | selector := (‘formatWith, formatting) asSymbol. self perform: selector Still your class gets complex...
  • 7. S.Ducasse 7 Inheritance? May not be the solution since: - you have to create objects of the right class - it is difficult to change the policy at run-time - you can get an explosion of classes bloated with the use of a functionality and the functionalities. - no clear identification of responsibility
  • 9. S.Ducasse 9 When Many related classes differ only in their behavior You have variants of an algorithm (space/time) An algorithm uses data that the clients does not have to know
  • 11. S.Ducasse 11 Participants Strategy (Compositor) declares an interface common to all concrete strategies Concrete Strategies implement algorithm Context configure with concrete strategy maintains a reference to the concrete strategy may define an interface to let the strategy access data
  • 12. S.Ducasse 12 Collaborations (i) 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 GraphVisualizer>>graphIt .... grapher plot: data using: graphPane pen Grapher>>plot: data using: aPen
  • 13. S.Ducasse 13 Context passes itself as argument Also know as self-delegation... GraphVisualizer>>graphIt grapher plotFor: self BartChartGrapher>>plotFor: aGraphVisualizer |data| data := aGraphVisualizer data ....
  • 14. S.Ducasse 14 BackPointer Grapher class>>for: aGraphVisualizer ^ self new graphVisualizer: aGraphVisualizer BartChartGrapher>>plot ... graphVisualizer data.. graphVisualizer pen Grapher (Strategy) points directly to GraphVisualizer (Context), so sharing strategy between different context may be difficult, if sharing is needed then use self-delegation
  • 15. S.Ducasse 15 Collaboration (ii) “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.“ GOF Not sure that the client has to choose...
  • 16. S.Ducasse 16 Consequences Define a family of pluggable algorithms Eliminates conditional statements Clients can choose between several implementations Clients must be aware of the different strategies Increase the number of objects Communication overhead between client and strategies Weaken encapsulation of the client
  • 17. S.Ducasse 17 Domain-Specific Objects as Strategies Strategies do not have to be limited to one single algorithm They may represent domain specific knowledge Mortgage FixedRateMortgage OneYear...
  • 18. S.Ducasse 18 Known Uses ImageRenderer inVW: “a technique to render an image using a limited palette” ImageRenderer NearestPaint OrderedDither ErrorDiffusion View-Controller a view instance uses a controller object to handle and respond to user input via mouse or keyboard. Controllers can be changed at run-time