Friday, 23 March 2007

Strategy pattern

Strategy pattern

Strategy pattern is valuable where one algorithm has to be applied out of number of algorithms in real-time according to application needs.
The question in you mind must be that why use strategy and not if else or case statements, because that exactly what they do, choose one algorithm from others. An answer is yes it is similar but strategy pattern makes life easy. If-else and case statement can become very nested and complex. With strategy, to add another strategy or algorithm, strategy containing class code doesn’t have to be changed.
Good example from real life given by Pops[1] about credit card purchases. I’ll use UML diagram to explain better:


When we shop we can use different credit card it matter of choice which one to use. All creadit cards have different information in there magnetic strip, so these are different algorithms. Interface is the StripContents that is used while the implementation represents the TypeOfCard.

[1] Pops (n.d.) Components Tutorial, Retrieved from http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=strategyPattern

No comments: