Saturday, March 24, 2007

Factory of Patterns

Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.


<?php
class Factory
{
public static function driver($class_name)
{
if(include_once($class_name . ".php"))
{
return new $class_name;
}
else
{
// throw new Exception ("no such {$class_name}");
}
}
}

$a = Factory::driver('caller');
var_dump($a);
// $v = Factory::driver('mysql');
?>

No comments :