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

未匹配的标注
  • 策略模式:

策略模式设计帮助构建的对象不必自身包含逻辑,而是能够根据需要利用其他对象中的算法。

  • 使用场景:
  1. 例如有一个 CD 类,我们类存储了 CD 的信息。
  2. 原先的时候,我们在 CD 类中直接调用 getCD 方法给出 XML 的结果
  3. 随着业务扩展,需求方提出需要 JSON 数据格式输出
  4. 这个时候我们引进了策略模式,可以让使用方根据需求自由选择是输出 XML 还是 JSON
  • 代码实例:
<?php  

// 策略模式
// cd 类
class cd
{
    protected $cdArr;

    public function __construct($title, $info)
    {
        $this->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 version="0" encoding="utf-8"?>';
        $xml .= '<return>';
        $xml .= '<data>'.serialize($return_data).'</data>';
        $xml .= '</return>';
        return $xml;
    }
}

$cd = new cd('cd_1', 'cd_1');
echo $cd->getCd(new json);
echo $cd->getCd(new xml);

参考:《PHP 设计模式》Aaron Saray 著

原文#

blog.csdn.net/initphp/article/deta...

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
wangchunbo
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~