Thinking about the Builder and Factory patterns, I have had a hard time understanding the differences between the two. From reading this book, the factory pattern seems to return one instance of class from a group of classes that inherits from either from a common abstract class or interface. The factory class determines which class instance to return based upon an incoming parameter. Am I correct on that?
Now a builder class, simply returns a built instance of a class given paramters to build that class. Seems pretty close to what the factory patterns is. So I created some code that attempts to use both of these patterns. Let me know what you think.
I stick to the examples given in the book.
PHP Code:
<?php
interface CDInterface
{
public function setTitle($title);
public function setBand($band);
public function addTrack($track);
}
class StandardCD implements CDInterface
{
public $title = '';
public $band = '';
public $tracks = array();
public function setTitle($title)
{
$this->title = $title;
}
public function setBand($band)
{
$this->band = $band;
}
public function addTrack($track)
{
$this->tracks[] = $track;
}
}
class EnhancedCD implements CDInterface
{
public $title = '';
public $band = '';
public $tracks = array();
public function __construct()
{
$this->tracks[] = 'DATA TRACK';
}
public function setTitle($title)
{
$this->title = $title;
}
public function setBand($band)
{
$this->band = $band;
}
public function addTrack($track)
{
$this->tracks[] = $track;
}
}
interface Factory
{
public function create($type);
}
class CDFactory implements Factory
{
public function create($type)
{
$class = ucfirst(strtolower($type)) . 'CD';
return new $class;
}
}
class CDBuilder
{
private $factory;
public function __construct(Factory $factory)
{
$this->factory = $factory;
}
public function build($type, $title = '', $band = '', array $tracks = array())
{
$cd = $this->factory->create($type);
$cd->setTitle($title);
$cd->setBand($band);
foreach ($tracks as $track) {
$cd->addTrack($track);
}
return $cd;
}
}
$builder = new CDBuilder(new CDFactory);
$cd = $builder->build('Enhanced', 'Waste Of A Rib', 'Never Again', array('What It Means', 'Brrr', 'Goodbye'));
var_dump($cd);