Design Patterns Reference: Factory

“The Factory Design Pattern provides a simple interface to acquire a new instance of an object, while sheltering the calling code from the steps to determine which base class is actually instantiated.”
class standardCD
{
public $title = “”;
public $band = “”;
public $tracks = array();

public function __construct()
{
//
}

public function setTitle($title)
{
$this->title = $title;
}

public function setBand($band)
{
$this->band = $band;
}

public function addTrack($track)
{
$this->tracks[] = $track;
}
}

/**
* create a complete standardCD object
*/

$title = ‘Waste of a Rib’;
$band = ‘Never Again’;
$tracksFromExternalSource = array(‘What It Means’,’Brrr’,’Goodbye’);
$cd = new CD();
$cd->setTitle($title);
$cd->setBand($band);
foreach ($tracksFromExternalSource as $track)
{
$cd->addTrack($track);
}

/**
* another slight variation of a CD
* ‘enhanced’ is required as well
*/

class enhancedCD
{
public $title = “”;
public $band = “”;
public $tracks = array();

public function __construct()
{
//
}

public function setTitle($title)
{
$this->title = $title;
}

public function setBand($band)
{
$this->band = $band;
}

public function addTrack($track)
{
$this->tracks[] = ‘DATA TRACK’;
}
}

/**
* We could use conditional logic
* to determine which class to instantiate
* standardCD or enhancedCD
* but behold, instead, the Factory Pattern!
*/

class CDFactory
{
public static function create($type)
{
$class = strtolower($type) . “CD”;
return new $class;
}
}

/**
* Thus, to create a CD or an enhancedCD
*/

$type = ‘enhanced’; // or $type = ‘standard’;
$cd = CDFActory::create($type);
$cd->setBand($band);
$cd->setTitle($title);
foreach($tracksFromExternalSource as $track)
{
$cd->addTrack($track);
}

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

Leave a Reply

You must be logged in to post a comment.