Instructor: Stefan Mitsch
Strategy defines a family of algorithms and makes them interchangeable at runtime
Problem illustration: switching out algorithm needs recompilation
How to let application vary the encryption algorithm at runtime?
Problem
Several interchangeable algorithm implementations
Intent
Structure
The Context maintains a reference to one of the concrete strategies
Context
The Strategy interface declares methods for the Context to execute
Strategy
ConcreteStrategy classes implement different variants of the algorithm
ConcreteStrategy
The context calls the execute method on the linked strategy each time it needs to run the algorithm; the context does not know which one it uses.
execute
The Client creates a specific strategy object and passes it to the context; it then uses the context to execute the strategy
Client
// strategy interface public interface EncryptionStrategy { void encrypt(Message m); } // concrete strategies public class AESEncryptionStrategy implements EncryptionStrategy { public void encrypt(Message m) { /* ... */ } } public class BlowfishEncryptionStrategy implements EncryptionStrategy { public void encrypt(Message m) { /* ... */ } } // context public class EncryptionDecorator extends EmailDecorator { private EncryptionStrategy strategy; public final void send(Message m) { encrypt(m); super.send(m); } public void setStrategy(EncryptionStrategy s) { strategy = s; } private void encrypt(Message m) { strategy.encrypt(m); } }
Code Smell: Conditional logic in a method controls which fo several variants of a calcuation are executed
Before: Conditional logic for variants, frequently changes
Remaining: set the right strategy
Template Method
Command