一, 是什么
1. 定义: 让原来不兼容的两个接口协同工作
2. 分类: 类适配器, 对象适配器, 接口适配器
3. 角色
目标接口: Target, 该角色把其他类转换为我们期望的接口
被适配者: Adaptee 原有的接口, 也是希望被改变的接口
适配器: Adapter, 将被适配者和目标接口组合到一起的类
4. 类图
对象适配器, 使用组合
类适配器, 在 java 中实现不了, 需要多重继承才能实现, 类图是这个样子的, 当然如果变通一下, Target 是接口就可以了
接口适配器抽象方法
接口适配器的使用场景: 原有接口有很多方法, 而我们只需要其中一部分, 这是看可以用抽象类来实现该接口, 不需要的方法只需要写个空方法 (默认实现) 就好了, 接口目标类去实现自己需要的接口
适用的场景是不想实现原有类的所有方法
二, 示例
背景: 买了一个进口笔记本电脑
冲突: 笔记本电脑需要的三项电源, 和只提供的二项电源冲突
解决方案: 设置一个适配器二项充电口转化为三项充电口
2.1.1 Adaptee 原有的类 提供二项电
- /**
- * 插头 二项供电 Adaptee
- */
- public class TwoPower {
- public void powerByTwo() {
- System.out.println("提供二项供电");
- }
- }
2.1.2 Target 目标类 能输出三项供电
- /**
- * 插头提供三项供电 (target)
- */
- public interface ThreePower {
- /**
- * 三项供电
- */
- void powerByThree();
- }
2.1.3 对象适配器, 转换类 Adapter
- /**
- * 二项转三项的适配器 组合的方式 对象适配器
- */
- public class TwoToThreeAdapter implements ThreePower{
- /**
- * 使用委托来完成适配
- */
- private TwoPower twoPower;
- public TwoToThreeAdapter(TwoPower twoPower) {
- this.twoPower = twoPower;
- }
- @Override
- public void powerByThree() {
- System.out.println("借助组合适配器转化二项电");
- twoPower.powerByTwo();
- }
- }
2.1.4 类适配器 转换类 Adapter
- /**
- * 二项转三项的适配器 继承的方式 类
- */
- public class TwoToThreeAdapter2 extends TwoPower implements ThreePower {
- @Override
- public void powerByThree() {
- System.out.println("借助继承适配器转化二项电");
- this.powerByTwo();
- }
- }
测试
- /**
- * 笔记本电脑 这是使用组合模式的 - 适配器模式
- */
- public class NoteBook {
- /**
- * 期望的三项供电接口
- */
- private ThreePower threePower;
- public NoteBook(ThreePower threePower) {
- this.threePower = threePower;
- }
- public static void main(String[] args) {
- // ============================ 继承方式的适配器使用 类适配器 =====================================
- ThreePower threePower1 = new TwoToThreeAdapter2();
- NoteBook noteBook1 = new NoteBook(threePower1);
- noteBook1.recharge();
- noteBook1.work();
- // ============================ 组合方式的适配器使用 对象适配器 =====================================
- // 现在只有二项供电
- TwoPower twoPower = new TwoPower();
- ThreePower threePower = new TwoToThreeAdapter(twoPower);
- NoteBook noteBook = new NoteBook(threePower);
- // 1. 充电
- noteBook.recharge();
- // 2. 工作
- noteBook.work();
- }
- public void work() {
- System.out.println("笔记本电脑开始工作!");
- }
- public void recharge() {
- // 使用三项充电
- threePower.powerByThree();
- }
- }
控制台显示:
提供二项供电
借助继承适配器转化二项电
笔记本电脑开始工作!
提供二项供电
借助组合适配器转化二项电
笔记本电脑开始工作!
三, 总结
适配器好处
重用
复用的现存的类, 解决了现存类和复用环境要不一致的问题
低耦合
无需修改原有代码(遵循开闭原则)
这里说些缺点吧, 过多的使用适配器, 的确会让程序看起来很难懂, 我的理解是, 在适配别人接口和其他 API 接口时, 适配器的用处就来了
来源: https://www.cnblogs.com/milicool/p/11278617.html