DEV Community

菜皮日记
菜皮日记

Posted on

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

结构型设计模式-适配器 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);
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay