美文网首页
设计模式-适配器

设计模式-适配器

作者: Wu杰语 | 来源:发表于2020-12-03 21:25 被阅读0次

适配器模式,目的是为了适配补偿,对于适配器模式,我们要学习的两种方式是类适配器和对象适配器。

类适配器

interface Target {
  void f1();
  void f2();
}

abstract class Adaptee {
  void f1() {
  }
  void t1();
}

class Adaptor extends Adaptee implements Target {
  void f2() {
    t1();
  }
}

类适配器是尽量复用的思路。

对象适配器

interface Target {
  void f1();
  void f2();
}

class Adaptor  implements Target {
  void f1() {
     // do something
  }
  void f2() {
    // do something
  }
}

对象适配器是更加通用常用的方式。

小结

适配器模式,可以封装有缺陷的接口,设计替换依赖的外部系统,适配不同格式的数据等。

相关文章

网友评论

      本文标题:设计模式-适配器

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