Real world examples of Factory Method pattern
An example php code with static creation:
interface DbTable
{
public function doSomething(): void;
}
class MySqlTable implements DbTable
{
public function doSomething(): void
{ }
}
class OracleTable implements DbTable
{
public function doSomething(): void
{ }
}
class TableFactory
{
public static function createTable(string $type = null): DbTable
{
if ($type === 'oracle') {
return new OracleTable();
}
return new MySqlTable(); // default is mysql
}
}
// client
$oracleTable = TableFactory::createTable('oracle');
$oracleTable->doSomething();
To make it more dynamic (less modification later):
interface DbTable
{
public function doSomething(): void;
}
class MySqlTable implements DbTable
{
public function doSomething(): void
{ }
}
class OracleTable implements DbTable
{
public function doSomething(): void
{ }
}
class TableFactory
{
public static function createTable(string $tableName = null): DbTable
{
$className = __NAMESPACE__ . $tableName . 'Table';
if (class_exists($className)) {
$table = new $className();
if ($table instanceof DbTable) {
return $table;
}
}
throw new \Exception("Class $className doesn't exists or it's not implementing DbTable interface");
}
}
$tbl = TableFactory::createTable('Oracle');
$tbl->doSomething();
A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle, you will need to modify all your code, if you haven’t written your code following factory design pattern.
In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.