您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP设计模式系列 - 策略模式

2024/4/8 4:07:41发布14次查看
策略模式:
策略模式设计帮助构建的对象不必自身包含逻辑,而是能够根据需要利用其他对象中的算法。
使用场景:
例如有一个cd类,我们类存储了cd的信息。
原先的时候,我们在cd类中直接调用getcd方法给出xml的结果
随着业务扩展,需求方提出需要json数据格式输出
这个时候我们引进了策略模式,可以让使用方根据需求自由选择是输出xml还是json
代码实例:
cdarr['title'] = $title; $this->cdarr['info'] = $info; } public function getcd($typeobj) { return $typeobj->get($this->cdarr); } }class json { public function get($return_data) { return json_encode($return_data); }}class xml { public function get($return_data) { $xml = ''; $xml .= ''; $xml .= '' .serialize($return_data). ''; $xml .= ''; return $xml; }}$cd = new cd('cd_1', 'cd_1');echo $cd->getcd(new json);echo $cd->getcd(new xml);
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product