Tuesday, February 20, 2007

 
Strategy Method Pattern:

The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

Here an object and its behaviour are separated and put into two different classes. This allows to switch the algorithm that we are using at any time. To implement the strategy pattern, we are required to define a shared interface for all algorithms. Then we can implement these interfaces.

Let's say we have an interface which should change its behaviour depending on the country from where client is logged in. We first would identify the behaviours, and for each behaviour, we would create a class holding those in form of methods. And to make sure these methods are uniformly applied thoughout, we declare an interface with these methods.

Let's say the interface is something like this



interface sample
{
function MakeGreeting();
function FormatDate();
}



Now we identified the set of methods,

Now let's make the classes with strategies,


class USA implements sample
{
public function MakeGeeting()
{
echo 'Hello';
}
public functon FormatDate()
{
$dData = date("F j, Y, g:i a");
return $dData;
}
}

class India implements Sample
{
public function MakeGeeting()
{
echo 'Namastey';
}
public functon FormatDate()
{
$dData = date("j, F, Y, g:i a");
return $dData;
}
}


Now we have two startegies with us, which could grow with time, but this will hardly force us to make any changes in any of the existing codes anywhere. And moreover, we are not required to use those nested if or switches.

Let's now apply these,



function __autoload($country)
{
require_once $country . '.php';
}
$country = 'usa';
$cntry = new $country;

//test formatting
print($cntry->MakeGeeting() . "
\n");
print('Today is: ');
print($cntry->FormatDate() . "
\n");
?>

So the implementation is cool. Right?

So we can conclude that when we have several objects that are basically the same, but differ only in their behaviour, it is a good idea to make use of the Strategy Pattern.

Using Strategies, we can reduce these several objects to one class that uses several Strategies.

That's all for the day...will get back with some more

patterns soon....

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?