适配器模式,属于结构性模式中最简单的模式之一,主要的作用就是将原本不通用的接口或者方法,通过中间层的转换使其使用于新的需求,说白了就算我们从来没有学习过设计模式,遇到这种问题也能轻松的解决掉,只不过别人给起了一个高大上的名字而已
现在我们用php写了一个活动天气的接口,这个接口里面返回的数据使用serialize进行了序列化处理,本来其他客户端获取数据后再使用反序列化处理就完全没有问题,但是过一段时间后我们增加了一个使用go语言开发的客户端也要使用这个天气接口,但是go语言没法跟php一样使用反序列化解析数据就导致数据不兼容的问题出现,这时候就可以使用适配器模式来解决我们的问题
/**
* 定义天气类,获取天气
* Class Weather
*/
class Weather
{
/**
* 获取天气
*/
public function getWeather()
{
$weather = [
'temp' => '18',
'hum' => '20%',
'wea' => '多云'
];
return serialize($weather);
}
}
/**
* 定义天气适配器接口
* Interface WeatherAdapter
*/
interface WeatherAdapter
{
public function __construct(Weather $weather);
public function getWeather();
}
/**
* 定义go程序获取天气的类,这个类实现了天气适配器,所以go客户端只需要调用这个类就可以获取到go能解析的数据了
* Class GoWeather
*/
class GoWeather implements WeatherAdapter
{
private $weather;
public function __construct(Weather $weather)
{
$this->weather = $weather;
}
public function getWeather()
{
// TODO: Implement getWeather() method.
$data = $this->weather->getWeather();
$data = unserialize($data);
return json_encode($data, 256);
}
}
//客户端调用
$goWeather = new GoWeather(new Weather());
echo $goWeather ->getWeather();