| Adapter类,通过继承 src类,实现 dst 类接口,完成src->dst的适配 |
| 充电器本身相当于Adapter,220V交流电相当于src (即被适配者),我们的目dst(即 目标)是5V直流电 |

| package com.atguigu.adapter.classadapter; |
| |
| public class Voltage220V { |
| |
| public int output220V() { |
| int src = 220; |
| System.out.println("电压=" + src + "伏"); |
| return src; |
| } |
| } |
| |
| package com.atguigu.adapter.classadapter; |
| |
| public interface IVoltage5V { |
| public int output5V(); |
| } |
| |
| package com.atguigu.adapter.classadapter; |
| |
| public class VoltageAdapter extends Voltage220V implements IVoltage5V { |
| @Override |
| public int output5V() { |
| |
| |
| int srcV = output220V(); |
| int dstV = srcV / 44 ; |
| return dstV; |
| } |
| } |
| |
| package com.atguigu.adapter.classadapter; |
| public class Phone { |
| |
| public void charging(IVoltage5V iVoltage5V) { |
| if(iVoltage5V.output5V() == 5) { |
| System.out.println("电压为5V, 可以充电~~"); |
| } else if (iVoltage5V.output5V() > 5) { |
| System.out.println("电压大于5V, 不能充电~~"); |
| } |
| } |
| } |
| |
| package com.atguigu.adapter.classadapter; |
| public class Client { |
| public static void main(String[] args) { |
| System.out.println(" === 类适配器模式 ===="); |
| Phone phone = new Phone(); |
| phone.charging(new VoltageAdapter()); |
| } |
| } |
| 1) Java是单继承机制,所以类适配器需要继承src类这一点算是一个缺点, 因为这要求dst必须是接口,有一定局限性; |
| 2) src类的方法在Adapter中都会暴露出来,也增加了使用的成本。 |
| 3) 由于其继承了src类,所以它可以根据需求重写src类的方法,使得Adapter的灵活性增强了 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
2021-08-31 vue开发:前端项目模板