加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

策略模式

发布时间:2020-12-14 04:46:28 所属栏目:百科 来源:网络整理
导读:原文链接:http://www.orlion.ga/714/ 解释: ????策略模式帮助构建的对象不必包含本身的逻辑,而是能够根据需要利用其他对象中的算法。 ? 需求: ????我们本来有一个CD类: class?CD{private?$title;private?$band;public?function?__construct($title?,?$b

原文链接: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?StrategyCDStrategy('what?'?,?'Simple?Plan');

$xml?=?new?StrategyCDAsXMLStrategy();
$cd->setStrategyContext($xml);
echo?$cd->get();
echo?'<br/>';
$json?=?new?StrategyCDAsJSONStrategy();
$cd->setStrategyContext($json);
echo?$cd->get();

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读