适配器模式
来源:互联网 发布:网络直播加速 编辑:程序博客网 时间:2024/05/17 03:51
适配器模式把一个类的接口转换成客户端所期待的另一种接口,从而使原本因接口不匹配而不兼容的两个类能够在一起工作。
缺省适配器模式为一个接口提供缺省实现,这样子类型可以从这个缺省实现进行扩展,而不必从原有接口进行扩展。适配器模式的用意是改变源角色接口形式,以便于与目标接口相兼容,缺省的适配器用意则是为了方便建立一个不平庸的适配器类而提供的一种平庸的实现。
适配器模式有类的适配器模式和对象的适配器模式:
- 类适配器模式使用继承的方式,是静态的定义方式;对象适配器模式使用组合的方式,是动态的定义方式;
- 类的适配器模式可以重定义源角色的部分行为,相当于子类覆盖父类的部分方法;对象的适配器需要定义源角色的子类来实现重定义,然后组合子类;当想要增加一些新的行为时使用对象的适配器模式很方便且可同时适用于所有的源角色;
- 对于对象适配器,一个适配器可以把不同的源适配到同一目标;
示例:
class Apple { public void getAColor(String str) { System.out.println("Apple color is: " + str); }} class Orange { public void getOColor(String str) { System.out.println("Orange color is: " + str); }} class AppleAdapter extends Apple { private Orange orange; public AppleAdapter(Orange orange) { this.orange = orange; } public void getAColor(String str) { orange.getOColor(str); }} public class TestAdapter { public static void main(String[] args) { Apple apple1 = new Apple(); Apple apple2 = new Apple(); apple1.getAColor("green"); Orange orange = new Orange(); AppleAdapter aa = new AppleAdapter(orange); aa.getAColor("red"); }}
多用聚合/组合,少用继承。
0 0
- 适配器及适配器模式
- 适配器及适配器模式
- 适配器模式(类适配器)
- 适配器模式(默认适配器)
- 适配器模式(对象适配器)
- 适配器模式-类适配器
- 适配器模式-对象适配器
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- orm2 中文文档 4.1 hasOne(多对一关系)
- MyBatis学习之一 MyBatis简介与配置MyBatis+Spring+MySql
- 调用 LoadLibraryEx 失败
- 二分查找
- java30.XML操作------使用Dom4j简单操作XML数据举例
- 适配器模式
- 感知机核心算法的两种理解!
- 读《深入理解计算机系统》的感悟~
- Java Swing JTable 表格【6:表格模型DefaultTableModel】
- 观察者模式
- 为什么应用程序用户启动时崩溃,使用xcode打开却不会
- android中通过ContentResolver获取媒体资源
- linux sed 批量替换多个文件中的字符串
- [leetcode] 109. Convert Sorted List to Binary Search Tree 解题报告