专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

设计模式之—适配器模式

1.适配器模式的定义

Adapter Pattern:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn’t otherwise because of incompatible interface.

将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够一起工作。

2.通用类图

适配器模式中有三个主要对象。

Target:

转换成的目标接口,即将其他类转换为此Target接口

Adaptee:

被转换的类

Adapter:

适配器,通过实现Target接口并继承Adaptee类,并重写Target接口方法来实现适配

类图如下: 76_1.png

实现代码如下: Target类:

public interface Target {

    /**
     * request
     */
    void request();
}

Adaptee类:

public class Adaptee {

    public void doSomething(){
        System.out.println("Do something!");
    }
}

Adapter类:

public class Adapter extends Adaptee implements Target {

    @Override
    public void request() {
        doSomething();
    }
}

Client类:

public class Client {

    public static void main(String[] args) throws Exception {
        Target target = new Adapter();
        target.request();
    }
}

3.优点

1、可以使两个无关联的类一起运行 2.灵活性好,当不需要此适配器的时候,只需要将此类摘除掉即可

4.总结

适配器模式通常用来解决在功能变动时,解决接口不相容的问题,在系统设计阶段不应该使用此中模式

文章永久链接:https://tech.souyunku.com/32243

未经允许不得转载:搜云库技术团队 » 设计模式之—适配器模式

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们