三种适配器模式浅谈

160 阅读2分钟

「这是我参与2022首次更文挑战的第18天,活动详情查看:2022首次更文挑战」。

一、类适配器模式

image.png 有一个打开文件的接口。

image.png 具体文档工具wps,我想要实现上面的open接口,直接可以打开pdf。

public class OneAdapter extends WpsDocument implements DocumentManager {
    //类适配器
    @Override
    public void open(String fileType, String fileName) {
        if ("pdf".equals(fileType)) {
            super.openPdf(fileName);
        } else {
            throw new RuntimeException("文件类型不正确");
        }
    }
}

此处就是要让DocmentManager的实现类能通过open打开pdf。

public class OneAdapterTest {
    public static void main(String[] args) {
        OneAdapter adapter = new OneAdapter();
        adapter.open("pdf","3423432");
    }
}

此处的例子就是说我们已经有了pdf管理工具wps的时候,我们如何使用这个wps,此处的目标就是实现用open打开pdf。这就是类适配器的实现方式。 image.png 类适配器是通过继承源类,实现接口的方法实现的。java种只能单继承,这就要求目标必须是接口。此外如果我还有另外的word工具,要使用还需要再写一个适配器去适应word的。

二、对象适配器模式

public class TowAdapter implements DocumentManager {
    //持有wps管理工具
    private WpsDocument002 wpsDocument002;

    public TowAdapter(WpsDocument002 wpsDocument002){
        this.wpsDocument002 = wpsDocument002;
    }
    @Override
    public void open(String fileType, String fileName) {
        if ("pdf".equals(fileType)) {
            wpsDocument002.openPdf(fileName);
        } else {
            throw new RuntimeException("文件类型不正确");
        }
    }
}

对象适配器

public class TowAdapterTest {
    public static void main(String[] args) {
        WpsDocument002 wpsDocument002 = new WpsDocument002();
        TowAdapter adapter = new TowAdapter(wpsDocument002);
        adapter.open("pdf","3423432");
    }
}

对象适配器是通过持有该对象的方式实现适配,如果我还有word工具,还可以持有word工具,根据文件类型选择使用不同的工具。 image.png

三、接口适配器模式(缺省适配器模式)

public interface FileManager {
    void openPdf(String fileName);

    void openWord(String fileName);

    void openJpg(String fileName);
}

需要适配的目标,此处有3个需要适配的接口

public abstract class MediumAdapter implements FileManager{
    @Override
    public void openPdf(String fileName) {

    }

    @Override
    public void openWord(String fileName) {

    }

    @Override
    public void openJpg(String fileName) {

    }
}

中间适配器,实现了3个目标哦

public class ThreeAdapter extends MediumAdapter{
    private WpsDocument002 wpsDocument002;

    public ThreeAdapter(WpsDocument002 wpsDocument002){
        this.wpsDocument002 = wpsDocument002;
    }

    @Override
    public void openPdf(String fileName) {
        wpsDocument002.openPdf(fileName);
    }
}

具体适配器,仅仅适配了pdf的打开。

public class ThreeAdapterTest {
    public static void main(String[] args) {
        WpsDocument002 wpsDocument002 = new WpsDocument002();
        ThreeAdapter adapter = new ThreeAdapter(wpsDocument002);
        adapter.openPdf("3423432");
    }
}

此处是接口适配器,接口适配器即有一个目标接口类,有多个接口,我们实际上只需要用到其中的一个,就通过中间适配器假装将所有接口都适配了,在具体的适配器种,具体的去处理自己要用的。(这里接口适配器使用这个例子有点不好,可能会想为啥不直接调用openPdf。换一种说法:要实现的是openPdf,wpsDocument002只能将文件转换为pdf,不能直接使用,转换过后文件才能打开) image.png