适配器模式

Updated on in 程序人生 with 0 views and 0 comments

1、简述

适配器模式使原本由于接口不兼容而不能一起工作的那些类可以一起工作。

适配器模式分为类适配器模式和对象适配器模式,却别在于被适配的对象是通过继承还是组合来完成。

适配器实现了接口转换,在不修改客户端或者目标类的前提下,使得目标类与客户端的接口兼容。

例如现在有一个220V的充电器,用户希望新增一个功能让这个充电器可以适配22V的设备,但是同时也需要保留220V的充电功能,这个时候就需要使用适配器模式,来保留他原来的功能,同时新增功能。

2、类适配器

类适配器通过继承被适配的对象来实现新接口功能的适配,ChargerAdapter中,继承charger220V保留了原来的方法,同时实现了新功能。在下面的代码中,Charger220V就是要适配的对象。

public class Charger220V {
    public int charging(){
        System.out.println("输出220V电压");
        return 220;
    }
}
public interface Charger100V {
    public int charging();
}
public class ChargerAdapter extends Charger220V implements Charger100V {
    @Override
    public int charging() {
        int charging = super.charging();
        System.out.println("将220V转化为100V");
        return new Double(charging/2.2).intValue();
    }
}

3、对象适配器

Java中,只能实现单继承,如果有多个对象需要适配,就可以使用对象适配器。

public class Charger220V {
    public int charging(){
        System.out.println("输出220V电压");
        return 220;
    }
}
public class Charger2200V {
    public int charging(){
        System.out.println("输出2200V电压");
        return 2200;
    }
}
public interface Charger100V {
    public int charging();
}
public class MultiChargerAdapter implements Charger100V {

    private Charger220V charger220V;
    private Charger2200V charger2200V;
    private String chargerType;

    public MultiChargerAdapter(Charger220V charger220V, Charger2200V charger2200V) {
        this.chargerType = "220";
        this.charger220V = charger220V;
        this.charger2200V = charger2200V;
    }

    public void setChargerType(String chargerType){
        this.chargerType = chargerType;
    }

    @Override
    public int charging() {
        if(chargerType.equals("220")){
            int value = charger220V.charging();
            System.out.println("将220V转化为100V");
            return new Double(value / 2.2).intValue();
        }else if(chargerType.equals("2200")){
            int value = charger2200V.charging();
            System.out.println("将2200V转化为100V");
            return value / 22;
        }else{
            System.out.println("不支持的转换格式");
            return 0;
        }
    }
}
public class TestAdapter {
    public static void main(String[] args){
        //类适配器测试
        Charger100V charger100V = new ChargerAdapter();
        charger100V.charging();

        //对象适配器测试
        MultiChargerAdapter multiChargerAdapter = new MultiChargerAdapter(new Charger220V(),new Charger2200V());
        multiChargerAdapter.setChargerType("220");
        multiChargerAdapter.charging();
        multiChargerAdapter.setChargerType("2200");
        multiChargerAdapter.charging();
        multiChargerAdapter.setChargerType("280");
        multiChargerAdapter.charging();
    }
}

4、和代理模式的区别

代理模式注重已有接口功能的控制、增强;适配器模式注重和新接口的兼容,强调接口转换。

二者都可以在不破坏原代码的前提下,实现新的功能需求


标题:适配器模式
作者:wenyl
地址:http://www.wenyoulong.com/articles/2020/12/22/1608620087581.html