首页 > 编程 > Java > 正文

轻松掌握Java适配器模式

2019-11-26 13:46:40
字体:
来源:转载
供稿:网友

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

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

企业级开发和常用框架中的应用:流接口,例如将字符流转换为字节流输出是用的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(); } }

相对而言,对象适配器通过组合的方式比类适配器通过集成的方式要更灵活,推荐平时使用对象适配器。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表