zoukankan      html  css  js  c++  java
  • 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="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);  

    转自:http://blog.csdn.net/initphp/article/details/7760383

  • 相关阅读:
    创建双向数据绑定 ng-model
    数据绑定指令
    ios操作系统输入完成后,键盘没有弹下去的问题
    anjularjs 指令(1)
    关于苹果手机模态框问题
    手机端页面中去除a标签点击时的默认样式
    ffsfsdsfsfd
    8、排列组合
    7、递归的二分查找
    6、递归
  • 原文地址:https://www.cnblogs.com/zhhtao/p/4414719.html
Copyright © 2011-2022 走看看