Thursday, May 29, 2008

Strategy pattern Usage:

Strategy pattern:

When requirement is to vary behaviour of the class dynamically we cant go for inheritance as it is tied to instance type. Strategy pattern is about separating dynamic behaviours from the class and proving way of switching between them.

I have used this pattern as follows:

Requirement:
There are 2 rate type trade booking. Real time trade booking and bench mark trade booking. For both booking there are 3 possible flows in which application can come from. All 3 flows have different behaviour for implementation. But most of the code is common for same flow in different rate types. So if I go for inheritance I will need to create 6 subclasses and any change in say flow1 has to be replicated in flow1 of other rate type as well.

Implementation:

Common abstract class for both rate type
Common abstract class for all flow types.
2 Implementation for AbstractTradeBooker
i) RtTradeBooker
ii) BMTradeBooker

3 implementation for AbstractTradeFlow
i) Flow1TradeFlow


Now any change in processing which is totally depedent on rate type can go in Implementation of AbstractTradeBooker and any change in some flow will go in particular implementation of AbstractTradeFlow.

There will be abstract method or may be constructor defined in AbstractTradeBooker to set instance of AbstractTradeFlow.

Also we can use template design pattern inside these abstract base classes which will define generic steps for processing and let implementation override and change implementation of specific step.

So here we have encapsulated part that is changing inside different trade flows.


Second requirement:

Consider your web application can forward request to some other application when user clicks on some link. Consider there are 2 ways of authentication of user to the new application. One can be using cookies and other using web services.

Now to decide which strategy to be used for authenticating user to this application depends upon some user level flag maintained by parent application. Based on this flag we have to decide dynamically how we will be authenticating this user to requested application.

This can be solved by having 2 implementation of the AuthenticationService. CookieBasedAuthentication and WebServiceBasedAuthenticationService and decide which instance based on the user flag at runtime.

No comments: