PHP设计模式系列 - 策略模式
来源:互联网 发布:php 序列化 编辑:程序博客网 时间:2024/06/03 19:47
- 策略模式:
策略模式设计帮助构建的对象不必自身包含逻辑,而是能够根据需要利用其他对象中的算法。
- 使用场景:
- 例如有一个CD类,我们类存储了CD的信息。
- 原先的时候,我们在CD类中直接调用getCD方法给出XML的结果
- 随着业务扩展,需求方提出需要JSON数据格式输出
- 这个时候我们引进了策略模式,可以让使用方根据需求自由选择是输出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="1.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著
- PHP设计模式系列 - 策略模式
- PHP设计模式系列 - 策略模式
- PHP设计模式系列 - 策略模式
- 设计模式系列--策略模式
- 设计模式系列--策略模式
- 设计模式系列:策略模式
- 【设计模式系列】--策略模式
- PHP设计模式系列(一):策略模式
- 【PHP设计模式】策略模式
- PHP设计模式--策略模式
- php设计模式 策略模式。
- PHP设计模式:策略模式
- php设计模式-策略模式
- PHP设计模式系列
- PHP设计模式系列
- PHP设计模式系列
- PHP设计模式系列
- PHP设计模式系列
- xCat在 虚拟机上部署系统
- 综合实例:AVR单片机(ATMEGA16)万年历(温度闹钟年月日时分秒星期)
- 百万级PHP网站架构工具箱
- break、continue和return在编程中的作用
- Android中常用的位图操作
- PHP设计模式系列 - 策略模式
- java线程 同步与异步 线程池
- JAVA 使用相对路径读取文件
- android 接入快盘 openapi 问题整理集合
- 为什么覆写equals的时候一定要覆写hashCode?
- String,StringBuffer与StringBuilder的区别
- Qt入门-基于QMainWindow的窗体
- http://acm.hdu.edu.cn/showproblem.php?pid=1106&&排序
- 如何实现类的成员函数作为回调函数