Aug
10
2010
10
2010
Design Patterns : Strategy pattern
Motivation
There are situations where the classes differ only by their behaviour, and on such situations it is advisable to isolate the algorithms into separate classes in order to have the ability to select different algorithms at the runtime depending on the user needs/client inputs.
Intent
- “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.” [Gamma, p315]
- Capture the abstraction in an interface, bury implementation details in derived classes.
Diagram

Code Sample
//StrategyExample test application
class StrategyExample { public static void main(String[] args) {Context context;
// Three contexts following different strategies
context = new Context(new FirstStrategy());
context.execute();
context = new Context(new SecondStrategy());
context.execute();
context = new Context(new ThirdStrategy());
context.execute();
}
}
// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {void execute();
}
// Implements the algorithm using the strategy interface
class FirstStrategy implements Strategy { public void execute() { System.out.println("Called FirstStrategy.execute()");}
}
class SecondStrategy implements Strategy { public void execute() { System.out.println("Called SecondStrategy.execute()");}
}
class ThirdStrategy implements Strategy { public void execute() { System.out.println("Called ThirdStrategy.execute()");}
}
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {Strategy strategy;
// Constructor
public Context(Strategy strategy) {this.strategy = strategy;
}
public void execute() {this.strategy.execute();
}
}
Related Posts
Recent Posts
- How to populate a dropdown menu from database in CodeIgniter [Workaround]
- How to Overclock Samsung Galaxy Mini Upto 800MHz
- Current and Future Relavance of Business Excellence / Improvement to Argos UK Ltd. Possible Benefits and Likely Inhabitors Exists
- What can Harm Your Online Reputation?
- Does Race Matter in the Choice of Popular Music among Youngsters?
The Tutebox
- Accounting
- Android Tips
- Apps
- Business
- C / C++
- Computers
- Database
- Design Patterns
- E-Commerce
- Economics
- Electronics
- Entertainment
- Finance
- Functional Programming
- Games
- Hardware
- Health
- HRM
- International Business
- Internet
- iOS Tips
- JAVA
- Life Style
- Linux
- M-Commerce
- Management
- Marketing
- Mathematics
- Mobile
- MS Office
- Network
- PC
- Personal Development
- Photography
- PHP
- Physics
- Places
- Programming
- Science
- Software
- Statistics
- Tweaks
- Visual Studio
- Web Hosting
- Windows

Article by




