Thursday, March 29, 2012

What is the Strategy design pattern?

What is the Strategy design pattern?
The Strategy design pattern can be used when a task, a processing or an algorithm can be done in different ways, to be decided at runtime, conditioned to a context. For instance, you may have different ways of drawing your domain object, according to the choice of the user. Instead of writing some "ugly" code using a Switch block, you can program to an interface. Program to a Strategy interface.
[UML Class Diagram] Strategy design pattern
As you can see in the picture, the Context object doesn't need to know which concrete Strategy is going to be used to execute the algorithm(). You can easily add new concrete strategies in the future. The choice for the strategy to be used could be done separately from the call to  algorithm().

No comments:

Post a Comment

Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.

Give a good example!