轻松掌握Java适配器模式
在计算机编程中,适配器模式(有时候也称包装样式或者包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
特点:将两个不兼容的类通过接口实现在一起工作
企业级开发和常用框架中的应用:流接口,例如将字符流转换为字节流输出是用的outputstreamreader
适配器模式分为类适配器和对象适配器:
举例:电脑只有USB接口,但是键盘只有圆口,这时就需要一个适配器,让键盘能输入数据到电脑
类适配器:
packagecom.test.adapter; publicclassComputer{ publicvoidshow(USBusb){ usb.recive(); System.out.println("电脑显示输入的数据"); } publicstaticvoidmain(String[]args){ Computerc=newComputer(); USBu=newUSBAdapter(); c.show(u); } } classKeyBoard{ publicvoidinput(){ System.out.println("键盘输入数据"); } } /** *适配器接口 */ interfaceUSB{ publicvoidrecive(); } /** *具体的适配器 */ classUSBAdapterextendsKeyBoardimplementsUSB{ publicvoidrecive(){ System.out.println("我是USB适配器,我使圆口的键盘能和USB接口电脑连接"); super.input(); } }
对象适配器:
packagecom.test.adapter; publicclassComputer{ publicvoidshow(USBusb){ usb.recive(); System.out.println("电脑显示输入的数据"); } publicstaticvoidmain(String[]args){ Computerc=newComputer(); KeyBoardk=newKeyBoard(); USBu=newUSBAdapter(k); c.show(u); } } classKeyBoard{ publicvoidinput(){ System.out.println("键盘输入数据"); } } /** *适配器接口 */ interfaceUSB{ publicvoidrecive(); } /** *具体的适配器 */ classUSBAdapterimplementsUSB{ privateKeyBoardk; publicUSBAdapter(KeyBoardk){ this.k=k; } publicvoidrecive(){ System.out.println("我是USB适配器,我使圆口的键盘能和USB接口电脑连接"); k.input(); } }
相对而言,对象适配器通过组合的方式比类适配器通过集成的方式要更灵活,推荐平时使用对象适配器。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。