适配器模式

一、模式名

适配器, Adapter

二、解决的问题

适配器模式就像我们平常使用的手机充电器转接头,把通用接口转换为非通用的Type-C接口,这样使用Type-C接口充电的手机就能使用平常的充电器充电。

适配器模式也是如此,通过定义一个适配器类,将两个无法统一、无法适配的类整合,使得它们能在一起工作。一般适配器模式用于一个类想使用另外一个类的某些方法,但这两个类无法兼容,不是继承于同一个类或实现了同一个接口,无法使用代理,所以需要使用适配器模式。

三、解决方案

适配器模式分为两种,其一为对象适配器,其二为类适配器。

1. 对象适配器UML

clipboard

可以看到,在适配器类Adapter中,定义了需要适配类的对象adaptee,同时Adapter继承了目标类,适配器类可以通过调用adaptee的相应方法完成Target中的相关方法,这样客户端可以使用适配器类来完成相应操作。

实例代码如下所示,完成iphone Type-c接口的充电器适配普通充电器接口。

interface Iphone {
    public String charge(String type);
}

class ChargeAdapter implements Iphone {

    private CommonMobile commonMobile = new CommonMobile();

    @Override
    public String charge(String type) {
        String output = commonMobile.commonCharge(type);
        if (output.equals("common")) {
            System.out.println("common --> type-c");
            return "type-c";
        }

        return null;
    }
}

class CommonMobile {
    public String commonCharge(String type) {
        System.out.println("使用普通充电器");
        if (type.equals("220v")) {
            return "common";
        }

        return null;
    }
}

public class AdapterClient1 {
    public static void main(String[] args) {
        Iphone iphone = new ChargeAdapter();
        String charge = iphone.charge("220v");
        System.out.println(charge);
    }
}

2.类适配器UML

clipboard

类适配器通过继承Target,实现Adaptee接口,完成这两个接口的适配。

interface Iphone2 {
    String charge(String type);
}

class CommonMobile2 {
    public String commonCharge(String type) {
        System.out.println("使用普通充电器");
        if (type.equals("220v")) {
            return "common";
        }

        return null;
    }
}

class Adapter2 extends CommonMobile2 implements Iphone2{
    @Override
    public String charge(String type) {
        String s = commonCharge(type);
        if (s.equals("common")) {
            System.out.println("common --> Type-c");
            return "type-c";
        }

        return null;
    }
}

public class AdapterClient2 {
    public static void main(String[] args) {
        Iphone2 iphone2 = new Adapter2();
        iphone2.charge("220v");
    }
}

常见应用场景:

1. JDBC适配数据库

原文地址:https://www.cnblogs.com/glsy/p/11070975.html