策略模式
原文链接:http://www.orlion.ga/714/
解释:
策略模式帮助构建的对象不必包含本身的逻辑,而是能够根据需要利用其他对象中的算法。
需求:
我们本来有一个CD类:
class CD{ private $title; private $band; public function __construct($title , $band) { $this->title = $title; $this->band = $band; } public function getAsXml(){ $doc = new \DOMDocument(); $root = $doc->createElement('cd'); $root = $doc->appendChild($root); $title = $doc->createElement('title' , $this->title); $title = $root->appendChild($title); $band = $doc->createElement('band' , $this->band); $band = $root->appendChild($band); return $doc->saveXML(); } }
后来我们想让CD以JSON格式输出,这时可以直接加入一个getAsJson()方法,但是后期我们可能还会让CD以其他各种各样的方式输入,这个CD最后会变得十分臃肿存在很多实例不会调用的方法。这时就可以从类中取出这些方法将其添加到只在需要时创建的具体类中。
代码:
首先设计一个接口在这个接口里规定要实现方法:
namespace Strategy; interface ShowStrategy{ function show(CDStrategy $cd); }
然后是XML类:
namespace Strategy; class CDAsXMLStrategy implements ShowStrategy{ public function show(CDStrategy $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(); } }
接着是JSON类:
namespace Strategy; class CDAsJSONStrategy implements ShowStrategy{ public function show(CDStrategy $cd) { $json = []; $json['cd']['title'] = $cd->title; $json['cd']['band'] = $cd->band; return json_encode($json); } }
然后是应用策略模式后的CD类:
namespace Strategy; class CDStrategy{ public $title; public $band; protected $_strategy; public function __construct($title , $band) { $this->title = $title; $this->band = $band; } public function setStrategyContext(ShowStrategy $strategy) { $this->_strategy = $strategy; } public function get() { return $this->_strategy->show($this); } }
最后是App.php测试下:
require 'CDStrategy.php'; require 'ShowStrategy.php'; require 'CDAsXMLStrategy.php'; require 'CDAsJSONStrategy.php'; $cd = new Strategy\CDStrategy('what?' , 'Simple Plan'); $xml = new Strategy\CDAsXMLStrategy(); $cd->setStrategyContext($xml); echo $cd->get(); echo '<br/>'; $json = new Strategy\CDAsJSONStrategy(); $cd->setStrategyContext($json); echo $cd->get();