关于后端:结构型设计模式适配器-Adapter

4次阅读

共计 1414 个字符,预计需要花费 4 分钟才能阅读完成。

结构型设计模式 - 适配器 Adapter

date: April 13, 2021
slug: design-pattern-adapter
status: Published
tags: 设计模式
type: Page

简介

适配器模式是一种结构型设计模式,它能使接口不兼容的对象可能相互合作

角色

  • 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 多平台公布

正文完
 0