php设计模式

WBOY
Release: 2016-06-23 13:22:46
Original
879 people have browsed it

场景:要做个php的数据接口,返回xml格式的数据。

我们通常是这么写的。

class Data{    private $_data = array();    public function __construct( $data ){        $this -> data = $data;    }        public function formatXml( $data ){        $xml = '<?xml version="1.0" encoding="utf-8"?>';          $xml .= '<return>';          $xml .= '<data>' .serialize($return_data). '</data>';          $xml .= '</return>';          return $xml;    }        //返回xml数据    public function getXml(){       // 怎样把数据处理成xml就不写了        return $this -> formatXml($this -> _data);    }}$data = new Data( array('title' => 'Strategy', 'language' => 'PHP')  );echo $data -> getXml();
Copy after login

那么问题来了,我需求要变了,这次要返回个JSON格式的,我该怎么处理呢?最简单的方法,在Data类里面再加入个getJson方法。问题虽然解决了,但记不记得我们之前讲的设计模式原则,对的,他违反了开闭原则。对扩展开放,对修改关闭。Data类的作用太复杂了,违反了单一职责原则。那么我们就要想办法了。

class Data{    private $_data = array();    public function __construct( $data ){            $this -> _data = $data;    }        //    public function getData( IFormat $format ){        $format -> formatData( $this -> _data );    }}interface IFormat{    public function formatData();}class Json implements IFormat{    public function formatData( $data ){        return json_encode( $data );    }}class Xml implements IFormat{    public function formatData( $data ){        $xml = '<?xml version="1.0" encoding="utf-8"?>';          $xml .= '<return>';          $xml .= '<data>' .serialize($return_data). '</data>';          $xml .= '</return>';          return $xml;    }}$data = new Data( array('title' => 'Strategy', 'language' => 'PHP') )$data -> getData( new Json() );  //获取Json格式$data -> getData( new Xml() );  //获取xml格式....//随便扩展
Copy after login

策略模式:类本身(Data)不包含处理策略(formatData),可以调用不通的策略对象(xml和Json)来实现不同策略的算法。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template