<?php
//策略设计模式构建的对象不必自身包含逻辑,而是能够根据需要利用其他对象中的算法。
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($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);
return $doc->saveXML();
}
}
class CDAsJSONStrategy{
public function get($cd){
$json = [];
$json['CD']['title'] = $cd->title;
$json['CD']['band'] = $cd->band;
return json_encode($json);
}
}
$externalBand = 'fenghuangchuanqi';
$externalTitle = 'zuixuanminzufeng';
$cd = new CDusesStrategy($externalTitle, $externalBand);
$cd->setStrategyContext(new CDAsXMLStrategy());
echo $cd->get();
echo PHP_EOL;
$cd->setStrategyContext(new CDAsJSONStrategy());
echo $cd->get();
//在能够创建应用于基对象的,由包含算法组成的可互换对象时,最佳的做法是使用策略设计模式。