Strategy Design Pattern
Hassan
Mukkram
What is a Design Pattern?
A software design pattern is a general, reusable
solution to a commonly occurring problem within a
given context in software design
Types of Design Patterns
Creational
Structural
Behavioural
Strategy is a behavioral design pattern
Strategy
In a Strategy design pattern, you will:
Define a family of algorithms
Encapsulate each one
Make them interchangeable
You should use Strategy when:
You have code with a lot of algorithms
You want to use these algorithms at different times
You have algorithm(s) that use data the client should
not know about
Strategy Class Diagram
ConcreteStrategyA
algorithmInterface()
ConcreteStrategyB
algorithmInterface()
ConcreteStrategyC
algorithmInterface()
Strategy
______________
Algorithminterface()
Context
contextInterface()
Strategy vs. Subclassing
Strategy can be used in place of subclassing
Strategy is more dynamic
Multiple strategies can be mixed in any combination
where subclassing would be difficult
Subclassing
 Subclassing Diagram
Class
functionX()
SubClass1
functionX()
SubClass2
functionX()
SubClass3
functionX()
Add a function
 Add functionY()
Class
functionX()
functionY()
SubClass1
functionX()
SubClass2
functionX()
SubClass3
functionX()
What happens?
 Need SIX classes to handle
both functions!!!
SubClass2
functionX()
functionY()
SubClass3
functionrX()
functionY()
SubClass2.1
behaviorY()
SubClass2.2
behaviorY()
SubClass1
____________
functionX()
functionY()
Class
___________
functionX()
functionY()
Strategy makes this easy!
 Diagram
Class
functionX()
functionY()
StrategyX
functionX()
...
StrategyY
functionY()
...
Benefits of Strategy
Eliminates conditional statements
Can be more efficient than case statements
Choice of implementation
Client can choose among different
implementations with different space and time
trade-offs
Continue…
Families of related algorithms
Alternative to subclassing
This lets you vary the algorithm dynamically, which
makes it easier to change and extend
You also avoid complex inheritance structures

Strategy design pattern

Editor's Notes

  • #4 behavioral design patterns are design patterns that identify common communication patterns among objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication
  • #13 Space-time or time-memory tradeoff is a way of solving a problem or calculation in less time by using more storage space (or memory), or by solving a problem in very little space by spending a long time
  • #14 Same type or group