Design Patterns Reference: Strategy

“The Strategy Design Pattern helps architect an object that can make use of algorithms in other objects on demand in lieu of containing the logic itself.”

 

class CDusesStrategy
{
public $title = ”;
public $band = ”;

 

protected $_strategy;

 

public function __construct($title, $band)
{
$this->title = $title;
$this->band = $band;
}

 

public function setStrategyContext($strategyObject)
{
$this->_strategy = $strategyObject;
}

 

public function get()
{
return $this->_strategy->get($this);
}
}

 

class CDAsXMLStrategy
{
public function get(CDusesStrategy $cd)
{
$doc = new DomDocument();
$root = $doc->createElement(‘CD’);
$root = $doc->appendChild($root);
$title = $doc->createElement(‘TITLE’, $cd->title);
$title = $root->appendChild($title);
$band = $root->createElement(‘BAND’, $cd->band);
$band = $root->appendChild($band);

 

return $doc->saveXML();
}
}

 

class CDAsJSONStrategy
{
public function get(CDusesStrategy $cd)
{
$json = array();
$json[‘CD’][‘title’] = $cd->title;
$json[‘CD’][‘band’] = $cd->band;

 

return json_encode($json);
}
}

 

// usage
$cd = new CDusesStrategy($externalTitle, $externalBand);

 

// xml output
$cd->setStrategyContext(new CDAsXMLStrategy());
print $cd->get();

 

// json output
$cd->setStrategyContext(new CDAsJSONStrategy());
print $cd->get($cd);

 

“When it’s possible to create interchangeable objects made of self-contained algorithms to be applied to a base object, it is best practice to use the Strategy Design Pattern”

 

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

 

 

Leave a Reply

You must be logged in to post a comment.