Académique Documents
Professionnel Documents
Culture Documents
Whats It For?
Sometimes need a different method depending on some
variable.
The methods will all solve the same problem, but in different ways.
if(almostSorted)
{
use class1.insertionSort();
}
else if(variable 2)
{
use class2.shellSort()
}
else if()
{
Low cohesion!
(Similar to Abstract Factory)
Using a Strategy
A solution to the previous code would be
strategy.sort(inventory);
}
Sorting Example
InventoryManager
SortInventory
+shellSort()
+insertionSort()
to use.
Inventories shouldnt have to decide about sorting algorithms!
Would an inventory manager at your local SuperMart or Burger
Queen be expected to know appropriate sorting strategies from
a data structures class?
Inheritance Encapsulation
Solution? (Not Really)
Inheritance often used to (poorly) solve this.
InventoryManager
SortInventory
+sort()
InsertionSort
+sort()
Shellsort
+sort()
Strategy Solution
InventoryManager
-Data data
if/else
in here
SortInventory
+sort(Data data)
SortStrategy
+sortAlgorithm()
InsertionSortStrategy
+sortAlgorithm()
ShellSortStrategy
+sortAlgorithm()
public SortInventory(
SortStrategy strategy)
{
this.strategy = strategy;
}
strategy.sortAlgorithm(data);
SortInventory
SortingPolicy
+sort(Data data)
-Data data
SortStrategy
+sortAlgorithm()
InsertionSort
+sortAlgorithm()
ShellSort
+sortAlgorithm()
if/else
in here.
Now if
customer
or boss
wants
different
Policy,
this is
easy to
replace.
Sort Code
Policy Code
return strategy;
Note: Common trick is to read the correct policy (business rules) from a configuration file.
Modem Example
ModemDriver
DialUpProtocol
+dial()
What can vary? How you dial up! The dial method.
Sometimes need a 1, sometimes need an
extension, sometimes need international prefix, etc.
So how would you solve this?
DialUpProtocol
Policy
+dialPhone()
IntlDialStrategy
+dial()
DialStrategy
+dial()
LocalDialStrategy
+dial()
return ds;
No!
Strategy Details
Purpose: Encapsulate related methods that
might change.
i.e., encapsulate a family of related algorithms.
i.e., encapsulate a family of business rules.
Strategy
Context
+algorithm()
ConcreteStrategy1
+algorithm()
ConcreteStrategy2
+ algorithm()
Strategy Consequences
Higher cohesion.
Greater flexibility/modularity.
Possible class explosion.
Methods must be related.
Each method should solve the same problem