美文网首页
设计模式(七)适配器模式

设计模式(七)适配器模式

作者: Active_Loser | 来源:发表于2019-06-20 23:51 被阅读0次

总章目录,设计模式(一)基本介绍

一、定义

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

二、类适配器

类适配器模式是把适配的类的API转换成为目标类的API,UML如下图所示:
客户端(Client):客户只会看到目标接口
目标(Target)接口:当前系统业务所期待的接口,它可以是抽象类或接口。
适配者(Adaptee)类:它是被访问和适配的现存组件库中的组件接口。
适配器(Adapter)类:它是一个转换器,通过继承或引用适配者的对象,把适配者接口转换成目标接口,让客户按目标接口的格式访问适配者


Target:
public interface Target {
    void Request();
}

Adaptee适配者:

public class Adaptee {
    public void SpecificRequest(){
        System.out.println("适配者接口!");
    }
}

Adapter适配器

public class Adapter extends Adaptee implements Target {

    @Override
    public void Request() {
        this.SpecificRequest();
    }
}

我们注意到Adaptee 中没有Request()方法,因此我们使用补充适配器这个方法。

public class Client {
    public static void main(String[] args){

        Target target = new Adapter();
        target.Request();
    }
}

输出:
适配者接口!

三、对象适配器

对象适配器与类的适配器模式相同,对象的适配器模式把适配的类的API转换成为目标类的API。


public interface Target {
    void Request();
}

public class Adaptee {
    public void SpecificRequest(){
        System.out.println("适配者接口!");
    }
}
public class Adapter implements Target  {
    // 直接关联被适配类
    private Adaptee adaptee;

    // 可以通过构造函数传入具体需要适配的被适配类对象
    public Adapter (Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void Request() {
        // 这里是使用委托的方式完成特殊功能
        this.adaptee.SpecificRequest();
    }
}
public class Client {
    public static void main(String[] args){

        Target target = new Adapter(new Adaptee());
        target.Request();
    }
}

四、总结

名称 优点 缺点
类适配器 复用性好,客户端可以调用同一接口,耦合性低。 高耦合,灵活性低
对象适配器 灵活性高、低耦合 需要引入对象实例

通常我们会使用对象适配器模式,避免使用继承。

相关文章

网友评论

      本文标题:设计模式(七)适配器模式

      本文链接:https://www.haomeiwen.com/subject/ohtfmqtx.html