适配器模式

作者: 孔祥子看天下 | 来源:发表于2017-03-16 11:25 被阅读29次

0x0 适配器模式介绍

要解决的问题

1、当一个新系统要是用老的系统的功能,而又发现接口不能融合时
2、系统需要使用现有的类,而此类的接口不符合系统的需要时。

组成

Target:客户期望的接口或者类
Adaptee:即将要适配的类
Adapter:适配器

好处

1、已经存在的类的接口不符合我们的需求;
2、创建一个可以复用的类,使得该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作;
3、在不对每一个都进行子类化以匹配它们的接口的情况下,使用一些已经存在的子类。

缺点

过多的使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是A接口,其实内部被适配成了B接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。

0x1 类图

适配器模式分2种,一种类模式,一种对象模式

类模式.png 对象模式.png

0x2 代码

Target
<pre>
public interface Target {

public void request();

}
</pre>

Adaptee
<pre>
public class Adaptee {

public void specialRequest() {
    System.out.println("special rqquest !");
}

}
</pre>

<pre>
//public class Adapter extends Adaptee implements Target { //这个是类模式
public class Adapter implements Target {//这个是对象模式的适配
Adaptee adaptee;

public Adapter( Adaptee adaptee ) {
    this.adaptee = adaptee;
}

@Override
public void request() {
    //适配
    this.adaptee.specialRequest();
}

}
</pre>

<pre>
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
Target target = new Adapter(new Adaptee());
target.request();
}
}
</pre>

相关文章

  • Java设计模式(二)

    talk is cheap show me the code 适配器模式 类适配器模式 接口适配器模式 对象适配器...

  • 适配器模式

    目录 1、什么是适配器模式? 2、适配器模式结构? 3、如何实现适配器模式? 4、适配器模式的特点? 5、适配器模...

  • 设计模式之适配器模式

    适配器模式: 类适配器模式、对象适配器模式、接口适配器模式 1.类适配器模式:新的接口出现了,但是和老的接口不兼容...

  • 学习iOS设计模式第一章 适配器(Adapter)

    今天学习了iOS设计模式中的适配器模式,适配器有两种模式对象适配器模式-- 在这种适配器模式中,适配器容纳一个它包...

  • 第4章 结构型模式-适配器模式

    一、适配器模式简介 二、适配器模式的优点 三、适配器模式的实例

  • 设计模式(Design Patterns)适配器模式(Adapt

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。 类的适配器模式 场景:将一个类转换成...

  • 适配器模式

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。适配器模式将某个类的接口转换成客户端期...

  • 适配器模式

    先直观感受下什么叫适配器 适配器模式有类的适配器模式和对象的适配器模式两种不同的形式。 类适配器模式 对象适配器模...

  • 适配器模式

    适配器模式 一、适配器模式定义 适配器模式的定义是,Convert the interface of a clas...

  • 设计模式:结构型

    享元模式 (Pools,Message) 代理模式 适配器模式 :类适配器和对象适配器 装饰者模式 外观模式 桥接...

网友评论

    本文标题:适配器模式

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