当前位置: 首页 > 科技观察

PC有电源适配器,设计模式也有适配器模式,你知道吗,

时间:2023-03-13 02:53:24 科技观察

01定义了适配器模式,将某个类的接口转换为客户端期望的另一个接口。主要目的是实现兼容性。接口不匹配,两个不能一起工作的类可以一起工作。02CategoryAdapterObjectAdapterInterfaceAdapter03外壳需要手机充电,通过手机充电器将220V电压适配为5V。方案一:类适配器定义220VAC(适配器角色)/***220VAC(适配器角色)*@author:liyajie*@createTime:2022/2/1721:41*@version:1.0*/publicclassAc{publicintoutputAc(){intsrcV=220;System.out.println(srcV+"交流电压");返回源码;}}定义5vDC(目标对象的作用)/***5vDC(目标对象的作用)*@author:liyajie*@createTime:2022/2/1721:44*@version:1.0*/publicinterfaceDc{intoutputDc();}defineadapter/***手机充电适配器*@author:liyajie*@createTime:2022/2/1721:45*@version:1.0*/publicclassPhoneAdapterextendsAcimplementsDc{@OverridepublicintoutputDc(){//获取220VACintsrcV=outputAc();//模拟适配器过程,转为5vDCinttargetV=srcV/44;系统输出。println("电压已经适配为"+targetV+"V");返回目标V;}}定义手机类/***手机类*@author:liyajie*@createTime:2022/2/1721:48*@version:1.0*/publicclassPhone{publicvoidcharge(Dcdc){if(dc.outputDc()==5){System.out.println("电压正常,可以安全充电");}else{System.out.println("电压异常,危险!");}}}定义测试类/***测试类*@author:liyajie*@createTime:2022/2/1810:56*@version:1.0*/publicclassTest{publicstaticvoidmain(String[]args){newPhone().charge(newPhoneAdapter());}}查看测试结果方案二:对象适配器本方案只需要修改手机适配器类,如下:/***手机充电适配器*@author:liyajie*@createTime:2022/2/1721:45*@version:1.0*/publicclassPhoneAdapterimplementsDc{privateAcac;publicPhoneAdapter(Acac){this.ac=ac;}@OverridepublicintoutputDc(){//获取220VACintsrcV=ac.outputAc();//模拟适配器过程,转为5vDCinttargetV=srcV/44;System.out.println("电压已经适配为"+targetV+"V");返回目标V;}}转换测试类/***测试类*@author:liyajie*@createTime:2022/2/1811:12*@version:1.0*/publicclassTest{publicstaticvoidmain(String[]args){新电话().charge(新电话适配器(新Ac()));}}查看测试结果方案三:接口适配器需要修改如下:定义一个默认适配器,用于实现Dc的多个方法,以便其他自定义适配器可以继承、扩展/***默认适配器*@author:liyajie*@createTime:2022/2/1721:45*@version:1.0*/publicclassDefaultAdapterimplementsDc{@OverridepublicintoutputDc(){return0;}}定义手机适配器/***手机充电适配器*@author:liyajie*@createTime:2022/2/1721:45*@version:1.0*/publicclassPhoneAdapterextendsDefaultAdapter{privateacac;publicPhoneAdapter(Acac){this.ac=ac;}@OverridepublicintoutputDc(){//获取220VACintsrcV=ac.outputAc();//模拟适配器过程,转为5vDCinttargetV=srcV/44;系统。out.println("电压已经适配为"+targetV+"V");返回目标V;}}定义手机类/***手机类*@author:liyajie*@createTime:2022/2/1721:48*@version:1.0*/publicclassPhone{publicvoidcharge(intv){if(v==5){System.out.println("电压正常,可以安全充电");}else{System.out.println("电压异常,危险!");}}}定义测试类/***测试类*@author:liyajie*@createTime:2022/2/1811:57*@version:1.0*/publicclassTest{publicstaticvoidmain(String[]args){newPhone().charge(newPhoneAdapter(newAc()).outputDc());}}查看测试结果04对比分析方案一:类Adapter优点:因为继承了adaptee,可以根据需要重写adaptee的方法,灵活性更好。缺点:由于继承是单继承属性,目标对象必须是接口,有一定的局限性。方案二:对象适配器改造适配类,继承适配类,修改为持有适配类,遵循组合重用原则,使用关联关系代替继承关系,进一步解耦,提高可扩展性。方案三:InterfaceAdapter接口适配器模式,也叫默认适配器模式,通过设计一个中间抽象类来实现接口,为接口中的每个方法提供默认实现,然后定义具体的适配器来继承默认适配器,只需要重写你需要重写的方法就够了。05总结适配器模式的三种实现方式。类适配器模式有一定的局限性。最常用的是对象适配器模式,所以推荐使用对象适配器模式。本文转载自微信公众号《温故知新java》,可通过以下二维码关注和转载本文,请联系温故知新java公众号。