Design Patterns Reference: Prototype

“In situations where a resource intensive object needs to be created often, the Prototype Pattern provides a welcome route to faster execution.”

 

“The Prototype Design Pattern creates objects in such a way that an initial object or prototype can be copied and cloned more efficiently than creating a new instance.”

 

class CD
{
public $band = ”;
public $title = ”;
public $trackList = array();

public function __construct($id)
{
$handle = mysql_connect(‘localhost’, ‘user’, ‘pass’);
mysql_select_db(‘CD’, $handle);

$query = “select band, title, from CDs where id={$id}”;

$results = mysql_query($query, $handle);

if ($row = mysql_fetch_assoc($results)){
$this->band = $row[‘band’];
$this->title = $row[‘title’];
}
}

 

public function buy()
{
// cd buying magic here
var_dump ($this);
}
}

 

class MixtapeCD extends CD
{
public function __close()
{
$this->title = ‘Mixtape’;
}
}

 

$externalPurchaseInfoBandID = 12;
$bandMixProto = new MixtapeCD($externalPurchaseInfoBandID);

 

$externalPurchaseInfo = array();
$externalPurchaseInfo[] = array(‘brrr’, ‘goodbye’);
$externalPurchaseInfo[] = array(‘what it means’, ‘brrr’);

 

foreach ($externalPurchaseInfo as $mixed) {
$cd = clone $bandMixProto;
$cd->trackList = $mixed;
$cd->buy();
}

 

“When working with objects whose creation is expensive and whose initial configuration stays relatively the same through new instances, using duplicate classes made with the Prototype Design Pattern is best practice.”

 

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

 

 

Leave a Reply

You must be logged in to post a comment.