Sunday, June 7, 2009

Design Pattern: Factory

Factory is a creational design pattern which handles object creation.
A factory class provides the methods to create object (whit a superclass in common), but let subclasses to decide which class will be instantiated.
Basically, it contains a static method ("connect" in the example below) that accept one parameter and makes a switch on it. Depending on the parameter, a new object of different type is returned. Typical use is when we have a super class A and subclasses A1, A2, An, and we add a static method getAx($name) { ... switching on $name and return a instance o A1 or A2... or An } .

Advantages: if we create a new type/subclass, we will not rewrite the code that create objects.

example:
Following, a class (factory) "DB" with a static method that returns an instance (object MySQL or postgreeSQL, that implements the same interface), in according to the argument (connection string).



class DB
{
public static connect($connString)
{
ereg("([a-z]*)://([a-z]*):([a-z]*)@([a-z]*)/([a-z]*)",$connString, $reg);
list($tmp, $driver, $user, $pass, $host, $db) = $reg;
switch($driver)
{
case "mysql": return new MySQL($host, $user, $pass, $db); break;
case "postgre": return new postgreSQL($user, $pass, $db, $host); break;
default: new Exception("connection string not valid !");
}
}


Example of use:
Now, let's use the factory, regardless the class type



$conn1 = DB:: connect("mysql://user:pass@localhost/db");
$conn2 = DB:: connect("postgre://user:pass@localhost/db");

//$conn1 and $conn will only use method of the common superclass/interface, ex: query()

No comments:

Post a Comment

 

PHP and tips|PHP