PHP design pattern series-policy pattern

Source: Internet
Author: User
& Nbsp; policy mode: the policy mode design helps to build an object that does not have to contain its own logic. Instead, it can use algorithms of other objects as needed. Use cases: for example, a CD class stores the CD information. In the past, we directly called the getCD method in the CD class to show the XML Results. as the business expands, the demand side proposed to output the results in JSON data format. at this time, we introduced the policy mode, users can choose whether to output XML or policy mode as needed:
Policy pattern design helps to build objects that do not have to contain logic, but can use algorithms of other objects as needed.

Use cases:
For example, a CD class stores CD information.
In the past, we directly called the getCD method in the CD class to give the XML results.
As the business expands, the demand side proposes to output data in JSON format.
At this time, we introduced a policy mode that allows users to choose whether to output XML or JSON as needed.
Code example:

 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. ='
 
  
'; $ Xml. ='
  '. Serialize ($ return_data ).''; $ Xml. ='
 '; Return $ xml ;}$ cd = new cd ('CD _ 1', 'CD _ 1'); echo $ cd-> getCd (new json ); echo $ cd-> getCd (new xml );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.