大家都来设计模式---适配器(Adapter)模式
来源:互联网 发布:Os软件 编辑:程序博客网 时间:2024/05/24 04:51
1. 概念
适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作
2. 应用场景
1) 系统需要使用现有的类,而此类的接口不符合系统的需要
2) 想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作,这些源类不一定有很复杂的接口
3) 在设计里,需要改变多个已有的子类的接口,如果使用类的适配器模式,就要针对每一个子类做一个适配器类,而这不太实际
3. 示例
大家对显卡都很熟悉,显卡又称为显示适配器,是电脑的最基本组成部分之一。为什么将显卡又称为显示适配器呢?还要从显卡的作用来说。显卡将计算机系统所需要的显示信息进行转换并驱动显示器,向显示器提供行扫描信号,控制显示器的正确显示。
上面的信息中涉及到三个硬件部分,由于显示器不能直接使用CPU提供的接口,所以由显卡在中间起到一个适配器作用,将CPU的接口数据转换成显示器所需要的数据格式
如图所示,GraphicInterface是提供图形数据的硬件接口;GraphicAdapter是显示适配器,负责CPU和显示器数据的转换 ;GraphicScreen是显示器,调用硬件接口获得数据并显示;CPU就不用说了。
示例代码:
GraphicInterface.java
public interface GraphicInterface {abstract String request();}
GraphicAdapter.java
public class GraphicAdapter implements GraphicInterface {private CPU cpu;public GraphicAdapter(CPU cpu) {this.cpu = cpu;}@Overridepublic String request() {String cpuData = cpu.request();return process(cpuData);}private String process(String cpuData) {return "graphic screen data :" + cpuData;}}
CPU.java
public class CPU {public String request() {return "show me";}}GraphicScreen.java
public class GraphicScreen {/** * @param args */public static void main(String[] args) {GraphicInterface graphicInterface = new GraphicAdapter(new CPU());String showData = graphicInterface.request();System.out.println(showData);}}
0 0
- 大家都来设计模式---适配器(Adapter)模式
- 设计模式--适配器(Adapter)
- 适配器Adapter 设计模式
- 设计模式--Adapter(适配器)
- 设计模式 - 适配器(Adapter)
- 适配器设计模式-Adapter
- Adapter(适配器)设计模式
- Adapter-适配器设计模式
- 设计模式:adapter适配器
- 设计模式--适配器模式(Adapter)
- 设计模式--适配器模式(Adapter)
- [设计模式]Adapter适配器模式
- 设计模式-适配器模式(adapter)
- 设计模式 -- Adapter 适配器模式
- 设计模式 - 适配器模式 Adapter
- 设计模式--适配器模式Adapter
- 设计模式:适配器模式-adapter
- 设计模式-适配器模式(Adapter)
- jQuery Mobile 导航栏
- 图文解说Keil MDK下ST-Link II的连接设置
- 数据库第三范式
- [ACM] hdu Lifting the Stone(多边形的重心)
- make: *** [out/target/common/obj/PACKAGING/checkapi-current-timestamp] 错误 38 处理
- 大家都来设计模式---适配器(Adapter)模式
- BroadcastReceiver的两种注册方式(静态注册和动态注册)
- 计算机网络
- 堆与栈的区别
- Mongodb源码分析--主程序入口main()
- 越狱团队否认收钱并中止与太极合作
- 解决 FtpClient 类无法导入 .
- Mongodb源码分析--日志及持久化
- 【Java算法学习】鸡兔同笼问题