美文网首页Android设计模式:入门到精通
Android 设计模式入门到精通之八:适配器模式(Adapte

Android 设计模式入门到精通之八:适配器模式(Adapte

作者: 编程家园 | 来源:发表于2020-02-04 10:57 被阅读0次

适配器模式(Adapter Pattern)

1. 概念

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interface. 适配器将一个类的接口转换成客户端所期待的另一种接口,让原本因为接口不匹配而无法在一起工作的两个类能在一起工作。

对象适配器

类适配器

2. 应用场景 

a. 用于扩展应用中,是一个补救模式,用来解决接口不相容的问题;

b. 项目一定要遵守依赖倒置原则、里氏替换原则,否则适配器也补救不了;


3. 适配器&外观&装饰者的区别

    • 适配器模式的意图:是改变接口以符合client的期望。

    • 外观模式的意图:是提供复杂子系统的一个简化接口,让接口更简单。

    • 装饰者模式的意图:是不改变接口,但加入新的行为和责任。


4. 优点

通过新增适配器:使得接口不同的两个类可以关联使用,并不改变原有类的代码结构;

5. 代码实践:

JDK: 

•java.util.Arrays#asList()

•javax.swing.JTable(TableModel)

•java.io.InputStreamReader(InputStream)

•java.io.OutputStreamWriter(OutputStream)

•javax.xml.bind.annotation.adapters.XmlAdapter#marshal()

•javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal()

Android: 

ListView.Adapter 

RecycleView.Adapter

相关文章

网友评论

    本文标题:Android 设计模式入门到精通之八:适配器模式(Adapte

    本文链接:https://www.haomeiwen.com/subject/smxrxhtx.html