要規定接口實現php
傳遞處理類和本身json
調用處理類的公共方法
this
<?php //策略模式 //對象接口 interface People { function outPut(OutDataFormat $odf); //輸出格式 } //學生 class Student implements People { public function outPut(OutDataFormat $odf) { return $odf->getData ( $this ); } } class Teacher implements People { public function outPut(OutDataFormat $odf) { return $odf->getData ( $this ); } } //配置格式模板 interface OutDataFormat { function getData(People $people); } class JsonFormat implements OutDataFormat { public function getData(People $people) { echo "json 格式"; return json_encode ( $people ); } } class XMLFormat implements OutDataFormat { public function getData(People $people) { $s = "<xml><name>"; $s .= $people->name; $s .= "</name></xml>"; return $s; } } $student = new Student (); $student->outPut ( new JsonFormat () );