星空网 > 软件开发 > ASP.net

适配器模式★★★★☆

一、什么是适配器

适配器是将一种接口改造成另外一种接口的一个包装类;

二、补充说明

有两种实现方式,一种是通过继承,另外一种通过组合;

使用组合实现的时候,跟装饰者模式有点类似,不过侧重点不同,装饰者模式是给对象增加新行为,适配器是为了适配接口;

优点:符合开闭原则;适配者类和目标类解耦;代码复用;

三、角色

目标接口

适配器类

适配者类

使用者

四、例子,JAVA实现

简介:现有一个USB接口和一个PSP接口实现类,功能都是进行充电,该例子的目的就是对PSP接口实现类进行包装,使之能用USB接口充电;

目标接口,使用USB接口充电

package com.pichen.dp.structuralpattern;public interface IUSB {		public void charge();	}

 一个USB接口的实现类(该类不属于适配器模式中的角色,只是一个对比)

package com.pichen.dp.structuralpattern;public class HPUSB implements IUSB{  @Override  public void charge() {    System.out.println("使用惠普USB接口充电~");      }}

适配者类,使用PSP充电

package com.pichen.dp.structuralpattern;public class PSP {  public void pspCharge(){        System.out.println("使用PSP接口充电~");      }}

适配器类(继承方式),继承PSP类,并实现IUSB接口

package com.pichen.dp.structuralpattern;public class PSPAdapter extends PSP implements IUSB{  @Override  public void charge() {    super.pspCharge();  }}

适配器类(组合方式),组合PSP对象,并实现IUSB接口

package com.pichen.dp.structuralpattern;public class PSPAdapter2 implements IUSB{  private PSP psp;    public PSPAdapter2(PSP psp) {    this.psp = psp;  }  @Override  public void charge() {    psp.pspCharge();  }  }

使用者Main,测试结果

package com.pichen.dp.structuralpattern;public class Main {  public static void main(String[] args) {    IUSB usb = new HPUSB();    usb.charge();        IUSB usb_psp = new PSPAdapter();    usb_psp.charge();        IUSB usb_psp2 = new PSPAdapter2(new PSP());    usb_psp2.charge();  }}

打印结果:

使用惠普USB接口充电~使用PSP接口充电~使用PSP接口充电~

 




原标题:适配器模式★★★★☆

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

大猫跨境:https://www.goluckyvip.com/tag/29651.html
大猫跨境物流:https://www.goluckyvip.com/tag/29652.html
大猫物流:https://www.goluckyvip.com/tag/29653.html
大鹏海关:https://www.goluckyvip.com/tag/29654.html
大鹏跨境电商:https://www.goluckyvip.com/tag/29655.html
大旗财税:https://www.goluckyvip.com/tag/29656.html
在古巴做游轮 古巴旅游项目:https://www.vstour.cn/a/363194.html
西藏旅游攻略自驾游需要多少天 去西藏旅游自驾游要多久时间:https://www.vstour.cn/a/363195.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流