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

  • 策略模式:

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

 

  • 使用场景:
    1. 例如有一个CD类,我们类存储了CD的信息。
    2. 原先的时候,我们在CD类中直接调用getCD方法给出XML的结果
    3. 随着业务扩展,需求方提出需要JSON数据格式输出
    4. 这个时候我们引进了策略模式,可以让使用方根据需求自由选择是输出XML还是JSON
  • 代码实例:
[php]  view plain  copy
 print ?
  1. <?php  
  2. //策略模式  
  3. //cd类  
  4. class cd {  
  5.     protected $cdArr;  
  6.       
  7.     public function __construct($title$info) {   
  8.         $this->cdArr['title'] = $title;  
  9.         $this->cdArr['info']  = $info;  
  10.     }  
  11.       
  12.     public function getCd($typeObj) {  
  13.         return $typeObj->get($this->cdArr);  
  14.     }   
  15. }  
  16.   
  17. class json {  
  18.     public function get($return_data) {  
  19.         return json_encode($return_data);  
  20.     }  
  21. }  
  22.   
  23. class xml {  
  24.     public function get($return_data) {  
  25.             $xml = '<?xml version="1.0" encoding="utf-8"?>';  
  26.             $xml .= '<return>';  
  27.                 $xml .= '<data>' .serialize($return_data). '</data>';  
  28.             $xml .= '</return>';  
  29.             return $xml;  
  30.     }  
  31. }  
  32.   
  33. $cd = new cd('cd_1''cd_1');  
  34. echo $cd->getCd(new json);  
  35. echo $cd->getCd(new xml);  

猜你喜欢

转载自blog.csdn.net/zhaanghao/article/details/52399960
今日推荐