您的位置:首页 > 编程语言 > Java开发

Java设计模式之十六(适配器模式)

2013-04-24 10:18 246 查看
一、什么是适配器模式

Adapter模式也叫适配器模式,是构造型模式之一,通过Adapter模式可以改变已有类(或外部类)的接口形式。

二、适配器模式应用场景

在大规模的系统开发过程中,我们常常碰到诸如以下这些情况:我们需要实现某些功能,这些功能已有还不太成熟的一个或多个外部组件,如果我们自己重新开发这些功能会花费大量时间;所以很多情况下会选择先暂时使用外部组件,以后再考虑随时替换。但这样一来,会带来一个问题,随着对外部组件库的替换,可能需要对引用该外部组件的源代码进行大面积的修改,因此也极可能引入新的问题等等。如何最大限度的降低修改面呢?Adapter模式就是针对这种类似需求而提出来的。Adapter模式通过定义一个新的接口(对要实现的功能加以抽象),和一个实现该接口的Adapter(适配器)类来透明地调用外部组件。这样替换外部组件时,最多只要修改几个Adapter类就可以了,其他源代码都不会受到影响。

三、适配器模式的结构

1.通过继承实现Adapter



2.通过委让实现Adapter



代码实现:

Adaptee类:

package com.qianyan.adapter;

public class Current {

public void use220V() {
System.out.println("使用220V电压");
}

}


Adapter类:

package com.qianyan.adapter;

public class Adapter1 extends Current {

public void use18V() {
System.out.println("使用适配器");
this.use220V();
}
}


package com.qianyan.adapter;

public class Adapter2 {

private Current current;

public Adapter2(Current current) {
this.current = current;
}

public void use18V() {
System.out.println("使用适配器");
this.current.use220V();
}
}


Client类:

package com.qianyan.adapter;

public class MainClass {

public static void main(String[] args) {
Adapter1 adapter1 = new Adapter1();
adapter1.use18V();

System.out.println("-------------");

Adapter2 adapter2 = new Adapter2(new Current());
adapter2.use18V();
}
}


测试结果:

使用适配器
使用220V电压
-------------
使用适配器
使用220V电压
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: