Definition
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
UML Class Diagram
Strategy: when and where use it
- The Strategy design pattern is widely used. Its intent is to encapsulate alternative strategies for a particular operation. The Strategy pattern is a "plug-and-play" pattern. The client calls a method on a particular interface which can be swapped out with any other Strategy class that implements the same interface. Strategy is useful in many different scenarios. An example is credit card processing. If a customer on an Shopping site prefers to pay with PayPal over 2Checkout the application can simply swap the PayPal strategy class out for the 2Checkout strategy class.
- If the Strategy interface has only a single method you can simplify the implementation by using a delegate rather than an interface. If you think about it, a delegate is a special case of the Strategy pattern. Therefore, you could argue that .NET?s event model (which uses delegates as eventhandlers) is built also on the Strategy pattern.
Sample
- Product
- IFilterStrategy
- Concrete strategy
- Client class
Ref: Gang of Four tutorial
No comments:
Post a Comment