php适配器模式
场景:向多个端提供接口,通过新类继承方式重新反回对应数据,不改变原来接口;
//假设使用php开发了一个天气接口
class Weather{ public static function show(){ $info = array( 'temperature' => '25°C', 'wind' => '西北风3~4级', 'weather' => '晴', 'PM2.5' => 60 ); return serialize($info); }}//PHP客户端调用$msg = Weather::show();$msg_arr = unserialize($msg);echo $msg_arr['weather'];//这时,如果java、python也要来调用天气接口,//但是不识别串行化后的字符串,但是又不能修改旧接口和旧php的调用//这时候可以用一个新的类继承,也就是适配器模式,来修改返回的数据格式为jsonclass WeatherAdapter extends Weather{ public static function show(){ $info = parent::show(); $info_arr = unserialize($info); return json_encode($info_arr); }} //java、python就可以使用返回的json进行使用$msg = WeatherAdapter::show();

浙公网安备 33010602011771号