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

Java设计模式之适配器模式

2016-08-23 00:00 225 查看
在计算机编程中,适配器模式(有时候也称包装样式或者包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。

特点:将两个不兼容的类通过接口实现在一起工作

企业级开发和常用框架中的应用:流接口,例如将字符流转换为字节流输出是用的outputstreamreader

适配器模式分为类适配器和对象适配器:

举例:电脑只有USB接口,但是键盘只有圆口,这时就需要一个适配器,让键盘能输入数据到电脑

类适配器:

package com.test.adapter;

public class Computer {

public void show(USB usb){
usb.recive();
System.out.println("电脑显示输入的数据");
}

public static void main(String[] args) {
Computer c = new Computer();
USB u = new USBAdapter();
c.show(u);
}
}

class KeyBoard{
public void input(){
System.out.println("键盘输入数据");
}

}

/**
*	适配器接口
*/
interface USB{
public void recive();
}

/**
* 具体的适配器
*/
class USBAdapter extends KeyBoard implements USB{

public void recive() {
System.out.println("我是USB适配器,我使圆口的键盘能和USB接口电脑连接");
super.input();
}

}

对象适配器:

package com.test.adapter;

public class Computer {

public void show(USB usb){
usb.recive();
System.out.println("电脑显示输入的数据");
}

public static void main(String[] args) {
Computer c = new Computer();
KeyBoard k = new KeyBoard();
USB u = new USBAdapter(k);
c.show(u);
}
}

class KeyBoard{
public void input(){
System.out.println("键盘输入数据");
}

}

/**
*	适配器接口
*/
interface USB{
public void recive();
}

/**
* 具体的适配器
*/
class USBAdapter implements USB{

private KeyBoard k;

public USBAdapter(KeyBoard k) {
this.k = k;
}

public void recive() {
System.out.println("我是USB适配器,我使圆口的键盘能和USB接口电脑连接");
k.input();
}

}

相对而言,对象适配器通过组合的方式比类适配器通过集成的方式要更灵活,推荐平时使用对象适配器。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息