设计模式之适配器模式

故事扮演 提交于 2020-02-08 00:13:52

适配器模式(Adapter Pattern)是指将一个类的接口转移成用户期望的另外一个接口,使原本接口不兼容的类可以一起工作,属于结构性设计模式。平常的充电器转换头就是一个适配器。

场景:

  • 已存在的类的方法和需求不匹配的情况

下面就以充电器转换头为例

  • android 充电器
public class MicroUSB {
    public void chargingHead(){
        System.out.println("android 充电接口");
    }
}
  • Type-C 转接头
public interface TypeC {
    void typeCConverter();
}
  • 苹果 转接头
public interface Iphone {
    void iphoneConverter();
}

  • 转接头适配器
public class ChargeAdapter implements TypeC,Iphone {
    private MicroUSB microUSB;

    public ChargeAdapter(MicroUSB microUSB) {
        this.microUSB = microUSB;
    }

    @Override
    public void typeCConverter() {
        microUSB.chargingHead();
        System.out.println("android接口变type-c 接口");
    }

    @Override
    public void iphoneConverter() {
        microUSB.chargingHead();
        System.out.println("android接口变 iphone 接口");
    }
}
  • 运行
public class Run {
    public static void main(String[] args) {
        ChargeAdapter adapter = new ChargeAdapter(new MicroUSB());
        adapter.typeCConverter();
        adapter.iphoneConverter();
    }
}
  • 结果
android 充电接口
android 接口变type-c 接口
android 充电接口
android 接口变 iphone 接口

源码

  • 优点
    • 提高类的透明性和复用性,原有的接口被复用,但不需要做修改
    • 目标类和适配器类解耦,提高程序扩展性
    • 符合开闭原则
  • 缺点
    • 可能会增加程序的复杂性
    • 增加阅读难度,降低代码可读性
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!