The policy pattern design helps to build an object that does not have to contain logic on its own, but can leverage the algorithms in other objects as needed.
- For example, there is a CD class, and our class stores the information for the CD.
- Originally, we called the Getcd method directly in the CD class to give the results of the XML
- As the business expands, the demand side presents the need for JSON data format output
- This time we introduced a strategy model that allows the user to freely choose whether to export XML or JSON based on demand.
<?PHP//Policy mode//CD class classCD {protected $CDARR; Public function__construct ($title,$info) { $this->cdarr[' title '] =$title; $this->cdarr[' info '] =$info; } Public functionGETCD ($TYPEOBJ) { return $TYPEOBJ->get ($this-Cdarr); } } classJSON { Public functionGet$return _data) { returnJson_encode ($return _data); } } classXML { Public functionGet$return _data) { $xml= ' <?xml version= ' 1.0 ' encoding= ' utf-8 '?> '; $xml. = ' <return> '; $xml. = ' <data> '.Serialize($return _data). ' </data> '; $xml. = ' </return> '; return $xml; } } $CD=NewCD (' Cd_1 ', ' cd_1 '); Echo $CD->GETCD (NewJSON); Echo $CD->GETCD (NewXML);
Transferred from: http://blog.csdn.net/initphp/article/details/7760383
PHP design mode Series-Strategy mode