CS 4773 Object Oriented Systems The Strategy Pattern
This material is from Chapter 9 of the Design Patterns Explained book.
- From the Gang of Four:
Design a family of algorithms, encapsulate each one, and make
them interchangeable.
Strategy lets the algorithm vary independently from clients that use them.
Guiding Principles
- Objects have responsibilities
- Different specific implementations of the responsibuilities are
manifested through the use of polymorphism.
- You need to manage several different implementations of what is
conceptually the same algorighm.
- Program to an interface, not an implementation
- Favor aggregation over inheritance
- Consider what should be variable in your design.
Example: Producing a bill of sale
- One of the things that needs to be calculated is sales tax.
- Different types of items are taxed differently:
food: no tax
clothing: no tax on items under $100 one weekend a year
others
Problem: you want to do things differently, depending on the input received.
Methods of handling variation
- Copy and Paste: Duplicate your code, and make the necessary changes
in one copy.
Have a different, independent bill of sale for each type of item
- switch statements or if-then-else
- function pointers (language must support this, e.g. C, C++, not Java)
Use different functions of calculating each type of tax
Set a function pointer to point to the appropriate function.
- inheritance: can be a good choice if used wisely.
In this case, choose one of the types as the base bill of sale class.
Others override the tax calculation method.
- delegation: find out what varies and include it its own class.
Make one new class for each possibility.
Each should implement a common interface.
Create an instance of the appropriate one of these in a new class.
(aggregation)
This uses inheritance (each tax class implements the tax interface),
but at a lower level.
This approach is often referred to as the strategy pattern.
Example from the editor
- Choose an EditorFile based on the contents of the file being edited.
- If the file is very long, a virtual representation of the file may be
appropriate.
- This would keep most of the file on disk, and cache only those lines
that have been recently requrested.
- Choose a GUI based on the contents of the file being edited.
- If the file contains only short lines of printing characters
(codes between ' ' and 127 and newline) the display could be simple.
- If the lines are long, you might want a GUI that can wrap lines.
- If the file contains non-printing characters, the GUI could display
characters as two hex digits.
- While all of this could be done with a single GUI, it might be
appropriate to have different groups implement different versions.
- Perhaps just a display class of the GUI would need to be modified.