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

Decorator Pattern


Decorator Pattern is used when components (instances of Component) are to be extended dynamically by functionality. Without changing the structure of a class, one class adds more functionality to other class.
Decorator eleminates the need for subclassing and add the additional behavior/funcionality at runtime.
I think decorator pattern can also be very helpful for coders when end user requests more additional features when task is almost complete. Because without changing the structure of one class coder can create another class with less effort and with less chances of logical errors, that will add all extra required features.

Adapter Pattern

As name implies Adapter pattern is used to allow incompatible classes/objects work together. Without modifying the client’s object who wishes to use another object whose interfaces or data types doesn’t match, adapter object/class can be implemented to solve the problem.

Adapter pattern can be applied for classes and for objects.
In Class Adapter;



the adapter class multiple inherits adoptee class and the clients target (interface) class. Because JAVA does not permit multiple inheritances, either one has to be adapted as Java interface type.

In Object Adapter;
In Object Adapter; Adapter contains the instance of the Adaptee and inherits the Client’s Target interface. When Client calls Target object the request is translated into request of the Adaptee object.

Image Source:
http://staff.aist.go.jp/y-ichisugi/ja/mj/design-pattern/fig-GoF/PNG/adapter1.png
http://staff.aist.go.jp/y-ichisugi/ja/mj/design-pattern/fig-GoF/PNG/adapter2.png