Scenario: To make a PHP data interface, return the data in XML format.
That's what we usually write.
Class data{ Private $_data = Array (); Public function __construct ($data) { $this, data = $data; } Public Function Formatxml ($data) { $xml = '
; $xml. = '
; $xml. = "
. Serialize ($return _data). ''; $xml. = '
; return $xml; } Returns the XML data public function getXml () { //How to convert data into XML without writing return $this-Formatxml ($this, _data); }} $data = new Data (Array (' title ' = ' strategy ', ' language ' = ' PHP ') ); Echo $data-getXml ();
So the problem comes, I need to change, this time to return a JSON format, how can I deal with it? The simplest way to do this is to add a Getjson method to the data class. Although the problem has been solved, but remember that we said the design model principle, right, he violated the opening and shutting principle. Open for extensions, close for modifications. The role of the data class is too complex to violate the principle of single responsibility. Then we'll have to find a way.
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. = '
; $xml. = "
. Serialize ($return _data). ''; $xml. = '
; return $xml; }} $data = new Data (Array (' title ' = ' strategy ', ' language ' = ' PHP ') ') $data, GetData (New Json ()); Gets the JSON format $data-getData (New Xml ()); Get XML Format ....//Expand casually
Policy mode: The class itself (Data) does not contain a processing policy (formatdata), and can invoke non-pass policy objects (XML and JSON) to implement algorithms for different policies.