适配器模式
2019-02-25 11:22 剑动情缥缈 阅读(186) 评论(0) 编辑 收藏 举报1.概念
- 适配器:定义一个包装类,用于包装不兼容接口的对象
包装类 = 适配器Adapter;
被包装对象 = 适配者Adaptee = 被适配的类
- 目的:由于接口不同而不兼容的两个类可以一起工作
2.类的适配器模式(通过继承实现)
- UML图
- 问题
Target期待调用Request方法,而Adaptee并没有(这就是所谓的不兼容了)。
- 解决方案
为使Target能够使用Adaptee类里的SpecificRequest方法,故提供一个中间环节Adapter类(继承Adaptee & 实现Target接口),把Adaptee的API与Target的API衔接起来(适配)。
- 代码实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.chengjie; interface Target { void request(); } class Adaptee { public void specificRequest() { System.out.println("Adaptee.specificRequest() is called"); } } class Adapter extends Adaptee implements Target { @Override public void request() { specificRequest(); } } public class TestAdapter { //本来无法将Adaptee应用于本方法,通过Adapter后可以 public static void test(Target target) { target.request(); } public static void main(String[] args) { test(new Adapter()); } }
3.对象的适配器模式(通过组合)
- UML图
- 问题
Target期待调用Request方法,而Adaptee并没有(这就是所谓的不兼容了)。
- 解决方案
为使Target能够使用Adaptee类里的SpecificRequest方法,故提供一个中间环节Adapter类(包装了一个Adaptee的实例),把Adaptee的API与Target的API衔接起来(适配)。
- 代码实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.chengjie; interface Target1 { void request(); } class Adaptee1 { public void specificRequest() { System.out.println("Adaptee1.specificRequest() is called"); } } class Adapter1 implements Target1 { private Adaptee1 adaptee; public Adapter1(Adaptee1 adaptee) { this.adaptee = adaptee; } @Override public void request() { adaptee.specificRequest(); } } public class TestAdapter1 { //本来无法将Adaptee1应用于本方法,通过Adapter1后可以 public static void test(Target1 target) { target.request(); } public static void main(String[] args) { test(new Adapter1(new Adaptee1())); } }
4.参考链接
https://blog.csdn.net/carson_ho/article/details/54910430