<?php
/**
* 适配器模式
* 适配器模式是将某个对象的接口适配为另一个对象所期望的接口
*
* 在需要转化一个对象的接口用于另一个对象时,最好实现适配器模式对象
*/
class Weather {
public $_info = NULL;
public function __construct() {
$this->_info = serialize(array('tep' => 24, 'wind' => 2));
}
public function show() {
return unserialize($this->_info);
}
}
//调用原始接口 序列化形式
$we = new Weather();
$array = $we->show();
echo '旧接口<br>';
echo "温度:" . $array['tep'] . "<br>";
echo "风力:" . $array['wind'] . "<br><br>";
class JsonAdapter extends Weather {
public function __construct() {
parent::__construct();
$tmp = unserialize($this->_info);
$this->_info = json_encode($tmp);
}
public function show() {
return json_decode($this->_info,TRUE);
}
}
//调用原始接口 序列化形式
$we = new JsonAdapter();
$array = $we->show();
echo '新接口<br>';
echo "温度:" . $array['tep'] . "<br>";
echo "风力:" . $array['wind'] . "<br>";