Design Patterns Reference: Facade

“The Facade Design Pattern hides complexity from a calling object by creating a simple facade interface in front of the collection of required logic and methods.”

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

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

/**
* build a CD
*/

$tracksFromExternalSource = array(‘What It Means’,’Brrr’,’Goodbye’);
$title = ‘Waste of a Rib’;
$band = ‘Never Again’;
$cd = new CD($title, $band, $tracksFromExternalSource);

class CDUpperCase
{
public static function makeString(CD $cd, $type)
{
$cd->$type = strtoupper($cd->$type);
}

public static function makeArray(CD $cd, $type)
{
$cd->$type = array_map(‘strtoupper’, $cd->$type);
}
}

class CDMakeXML
{
public static function create(CD $cd)
{
$doc = new DomDocument();

$root = $doc->createElement(‘CD’);
$root = $doc->appendChild($root);

$title = $doc->createElement(‘TITLE’, $cd->title);
$title = $root->appendChild($title);

$band = $doc->createElement(‘BAND’, $cd->band);
$band = $root->appendChild($band);

$tracks = $doc->createElement(‘TRACKS’);
$tracks = $root->appendChild($tracks);

foreach ($cd->tracks as $track){
$track = $doc->createElement(‘TRACK’, $track);
$track = $tracks->appendChild($track);
}
return $doc->saveXML();
}
}

/**
* instead of applying CDUpperCase & CDMake XML on CD object as follows:
*/

CDUpperCase::makeString($cd, ‘title’);
CDUpperCase::makeString($cd, ‘band’);
CDUpperCase::makeArray($cd, ‘tracks’);
print CDMakeXML::create($cd);

/**
* a facade object better serves the purpose!
*/

class WebServiceFacade
{
public static function makeXMLCall(CD $cd)
{
CDUpperCase::makeString($cd, ‘title’);
CDUpperCase::makeString($cd, ‘band’);
CDUpperCase::makeArray($cd, ‘tracks’);

$xml = CDMakeXML::create($cd);

return $xml;
}
}

/**
* thus implemented in ONE line instead, as follows:
*/

print WebServiceFacade::makeXMLCall($cd);

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

Leave a Reply

You must be logged in to post a comment.