结构型设计模式-适配器 Adapter
文章目录
简介
适配器模式是一种结构型设计模式, 它能使接口不兼容的对象能够相互合作
角色
Client 接口 / Target 目标接口
用户使用的接口
Adaptee
被适配的对象,原有方法不能直接给 client 使用
Adapter
适配器,实现 Target 接口,将 Adaptee 的方法改造成兼容 client 的形式,供 client使用
类图
图示,Adapter 持有 Service 对象实例,method 方法实现自 Client Interface,使 client 可以调用,method 内部逻辑则将 client 的入参转换后交给 service 处理

代码
class Target
{
public function request(): string
{
return "Target: The default target's behavior.";
}
}
class Adaptee
{
public function specificRequest(): string
{
return ".eetpadA eht fo roivaheb laicepS";
}
}
class Adapter extends Target
{
private $adaptee;
public function __construct(Adaptee $adaptee)
{
$this->adaptee = $adaptee;
}
public function request(): string
{
return "Adapter: (TRANSLATED) " . strrev($this->adaptee->specificRequest());
}
}
function clientCode(Target $target)
{
echo $target->request();
}
echo "Client: I can work just fine with the Target objects:\n";
$target = new Target();
clientCode($target);
$adaptee = new Adaptee();
echo "Client: The Adaptee class has a weird interface. See, I don't understand it:\n";
echo "Adaptee: " . $adaptee->specificRequest();
echo "Client: But I can work with it via the Adapter:\n";
$adapter = new Adapter($adaptee);
clientCode($adapter);output:
Client: I can work just fine with the Target objects:
Target: The default target's behavior.Client: The Adaptee class has a weird interface. See, I don't understand it:
Adaptee: .eetpadA eht fo roivaheb laicepSClient: But I can work with it via the Adapter:
Adapter: (TRANSLATED) Special behavior of the Adaptee.本文由mdnice多平台发布
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论