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....

Wednesday, February 07, 2007

 
Factory Method Pattern:
In software development, a Factory is the location in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage. Factory methods encapsulate the creation of objects. This can be useful if the creation process is very complex, for example if it depends on settings in configuration files or on user input. This method provides a common point for instantiation of any of the various classes depending on certain factors (often decided by configuration). It abstracts the process from the system. These classes implement a set of methods which are declared to the system either via an abstract class or an interface. By
forcing this constraint, we can be rest assured that provided an object, the methods executed against it by the system will correspond accordingly.

This can be very useful in certain cases, for example suppose we are required to design a database-operation package which is database independent . For this we want our codes, using the package not to get effected even if database shifts from one technology to the other. Let's say today we are using My Sql, but even if tomorrow we decide to go with Oracle we, should not be required to change our code. This flexibility can be easily achieved by employing Factory Method Pattern.

So first we will make an interface, declaring all the important methods, which we want to be defined in each and every class under this package. So our code would like something like,


Interface DB_Gateway
{
public function AddQuery();

public function ExecuteStep();

public function RollBack();

public function GetError();
}


Now once we have this interface we will make every class associated with database operation to implement it. Now we could have classes dedicated to database technology. For example we can design a class exclusively for MySql and so on.

The one for My Sql will be something like:



class cMySql Implements DB_Gateway
{

private $strDBName;

private $strUserName;

private $strPWD;

private $cHandle;

private $strQuery;

private $strStatus;

private static $stExists = NULL;


public function AddQuery($query)
{
//implementation here...
}

public function ExecuteStep()
{
//implementation here...
}
public function RollBack()
{
//implementation here...
}
public function GetError()
{
//implementation here...
}
....
....
}



similarly we can have more classes dedicated to the database technology.

Now we can have a class which would supply the correct object depending on the database technology configured. So our decider class would look like this:


class ObjDecider
{

private $strHost;
private $strDBName;
private $strUserName;
private $strPwd;
private $strType;
private $strVer;

public function SetType($type)
{
$this->strType = $type;
}


/*
* This method will return the correct object depending the type set in config
*
* @return object
*/

public function GetObject()
{
$objDB = '';

switch($this->strType)
{
case 'MySql':
$objDB = cMySql::Initialize($this->strHost, $this->UserName, $this->Pwd, $this->DBName);
break;
// and so on.....
}
return $objDB;
}
}



So now we need not worry about changing the codes anywhere as we know that all the objects will support all the methods defined and will work in same manner irrespective of database. So here we have abstracted the inner layout. So the real task and implementation is abstracted and hence better OOP approach.

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

Tuesday, February 06, 2007

 
DESIGN PATTERNS:

Starting this artcile I would cover different design patterns focusing PHP. But before I proceed, for those who are new to this, let me introduce you briefly to "Design Patterns".

According to Wikipedia, the free encyclopedia:

"A design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved."

Creating flexible, extensible and portable applications is largely dependent upon how well we decouple, a system from the process involved with object composition, creation and representation. Most of the time, it is possible to abstract these processes by creating patterns, which in turn should take some of the task and hence relasing the burden of object construction and class referencing.

Sometimes a single instance of a class is required to effectively manage a task. For example in database operation we need only one instance of object to be present in memory. In such cases Singleton pattern is ideal.


The Singleton pattern possesses two general features:

* The default class constructor cannot be called. Instead, it will be called through a designated class maintainer method that ensures only one instantiation is available at any given time.

* A static class member that holds a reference to the existing class resource identifier.



For example consider fraction of code from DB:

class cMySql
{
/**
* This should hold the value of DB Name
*
* @var string
*/
private $strDBName;

/**
* This should hold the username details for the DB
*
* @var string
*/
private $strUserName;

/**
* This holds the database password
*
* @var string
*/
private $strPWD;

/**
* This preserves the handle
*
* @var resource
*/
private $cHandle;

/**
* This holds the error messages generated during the execution
*
* @var string
*/
private $strStatus;

/**
* This attribute will make sure that only one resource is available at one time
*
* @var cMySql
*/

private static $stExists = NULL;


/**
* This method would intiate a db connection
* @param string $host
* @param string $User
* @param string $Pwd
* @param string $dbName
*/

static function Initialize($host, $usr, $pwd, $dbname)
{
$this->strHost = $host;
$this->strUserName = $usr;
$this->strPWD = $pwd;
$this->strDBName = $dbname;

if(self::$stExists === NULL)
{
self::$stExists = new cMySql();
}
return self::$stExists;
}

public function Connect()
{
$this->cHandle = mysql_connect($this->strHost, $this->UserName, $this->strPWD);
if($this->cHandle)
{
$cDB = mysql_select_db($this->strDBName, $cHandle);
}
else
{
$this->strStatus = 'Encountered an error while connecting to the host '.mysql_error();
}
}

....
....
}

Now this class functionality will make sure that at any given point of time, only one object will be initiated.



example
$objDB = '';

$objDB = cMySql::Initialize($this->strHost, $this->UserName, $this->Pwd, $this->DBName);
$objDB->Connect();
....
....
and so on...

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