Tuesday, 22 October 2013

Factory Design Pattern

The factory design pattern is a pattern that has some methods that create objects for you. You don't use new method directly to create the objects. 

When you want to change the types of objects created, you just change the factory. All other codes that use the factory change automatically.

For example, in PHP:

<?php

class ClassModelC {
  private $ModelC;  
  public function __construct($c)
  {
    $this->ModelC = $c;
  }
  public function getModel()
  {  return $this->ModelC; }
}
class ClassModelB {
  private $ModelB;
  public function __construct($b)
  {
    $this->ModelB = $b;
  }  
  public function getModel()
  {  return $this->ModelB; }
}

class ClassModelA {
  private $ModelA;
  public function __construct($b, $c)
  {
    $this->ModelA = $b->getModel().' '.$c->getModel();
  }
  public function getModel()
  {
    return $this->ModelA;
  }
}

class Factory{
    public function build($b, $c)
    {
        $classc = $this->buildC($c);
        $classb = $this->buildB($b);
        return $this->buildA($classb, $classc);
    }

    public function buildA($classb, $classc)
    {
        return new ClassModelA($classb, $classc);
    }

    public function buildB($b)
    {
        return new ClassModelB($b);
    }

    public function buildC($c)
    {
        return new ClassModelC($c);
    }
}

$factory = new Factory;
$obj     = $factory->build('Thunderbird','Jaguar');
print_r($obj->getModel());
print("\n");
?>

If in future, you want to change the object type, you can just change the factory method, as below.

class Factory_New extends Factory{
    public function build($b, $c)
    {
        return DatabaseObject($b, $c);
    }
}

4 comments: