标签:creat 委托模式 getname const struct private sharp code protect
通过分配或委托到其他对象,去除核心对象中的判决或复杂功能,动态添加新功能.
class A { public function song($songList) { foreach($songList as $val) { echo $val . ‘.mp3‘; } } } class B { public function song($songList) { foreach($songList as $val) { echo $val . ‘.wav‘; } } } class Delegate { private $obj; private $songList = array(); public function __construct() { } public function setDelegate($type) { $this->obj = new $type(); } public function addSong($name) { $this->songList[] = $name; } public function song() { $this->obj->song($this->songList); } } // 调用 $delegate = new Delegate(); $delegate->setDelegate(‘A‘); $delegate->addSong(‘rolling in the deep‘); $delegate->song();
特点:
每个委托的对象都拥有一个相同的public方法名.
动态创建委托对象.
委托模式下,委托对象是依据被委托者Delegate中不同的数据类型,来对数据做处理.数据还是Delegate中的,只有这样子,才能叫委托.这也是他区别工厂模式的一个重要特点.
构建的对象不必自身包含逻辑,而是根据需要利用其它对象中的算法.
我们为类的输出数据,同时提供json和xml格式,至于使用那么格式由外部调用者决定. class User { private $uid, $name; protected $strategy; public function __construct($uid, $name) { $this->uid = $uid; $this->name = $name; } public function getUid() { return $this->uid; } public function getName() { return $this->name; } // 设置策略 public function setStrategy($obj) { $this->strategy = $obj; } public function get() { return $this->strategy->get($this); } } class JsonStrategy { public function get(User $user) { return json_encode(array(‘uid‘ => $user->getUid(), ‘name‘ => $user->getName())); } } class XmlStrategy { public function get(User $user) { $doc = new DOMDocument(); $root = $doc->createElement(‘user‘); $root = $doc->appendChild($root); $elementUid = $doc->createElement(‘uid‘, $user->getUid()); $root->appendChild($elementUid); $elementName = $doc->createElement(‘name‘, $user->getName()); $root->appendChild($elementName); return $doc->saveXML(); } } $user = new User(‘1‘, ‘jack‘); $user->setStrategy(new XmlStrategy()); echo $user->get(); $user->setStrategy(new JsonStrategy()); echo $user->get();
标签:creat 委托模式 getname const struct private sharp code protect
原文地址:http://www.cnblogs.com/itfenqing/p/7750556.html