适配器模式(adapter)
来源:互联网 发布:泰安房产每日成交数据 编辑:程序博客网 时间:2024/06/07 11:48
模式名称:适配器
使用场景
当原有功能不能满足现有需求并且现有需求与原有功能相近
比如:Version2适配Version1
好处
原有功能是稳定的版本,不应该直接修改原有版本,直接增加一个适配器适配现有功能,当出现bug的时候就可以直接定位到适配器中
实现方式:
第一种
继承方式
第二种
委托方式
代码实现
/** * Created by tanghaibin on 2017/9/12. * * 目标接口,对外提供服务 */public interface Target { /** * 获取指定的电压 * @param voltage * @return */ String getVoltage(int voltage);}
/** * Created by tanghaibin on 2017/9/12. * * 转换电压为指定电压 充当适配器角色 继承方式实现 */public class Adapter extends Adaptee implements Target { private static final String unit = "V"; public String getVoltage(int voltage) { String oldVoltage = super.getVoltage(); System.out.println("原始电压:" + oldVoltage); System.out.println("转换电压...."); System.out.println("转换后:" + voltage + unit); return voltage + unit; }}
/** * Created by tanghaibin on 2017/9/12. * * 原始电压 充当 待适配对象角色 */public class Adaptee { /** * 返回240V电压 * @return */ public String getVoltage() { return "220V"; }}
/** * Created by tanghaibin on 2017/9/12. * * 客户端,使用指定的适配器获取指定的电压 * * Target---->>>>>Adapter------>>>Adaptee * * 使用场景 * 当原有功能不能满足现有需求并且现有需求与原有功能相近 * 比如:Version2适配Version1 * 好处 * 原有功能是稳定的版本,不应该直接修改原有版本,直接增加一个适配器适配现有功能,当出现bug的时候就可以直接定位到适配器中 * * 实现方式有两种 * 第一种 * 继承方式,适用于Target 为接口的时候 * 委托方式,适用于Target 为类的时候,因为java无法多继承,继承了Target就无法再次继承Adaptee */public class Client { public static void main(String[] args) { Target target = new Adapter(); target.getVoltage(10); }}
UML图
阅读全文
0 0
- Adapter模式 适配器模式
- 适配器模式(Adapter)
- 适配器模式(Adapter)
- 适配器(Adapter)模式
- 适配器模式(Adapter Pattern)
- ADAPTER(适配器)模式
- 适配器模式(adapter)
- Adapter适配器模式
- 适配器(Adapter)模式
- 适配器模式(Adapter Pattern)
- Adapter(适配器)模式
- 适配器模式(adapter)
- 适配器模式(Adapter)
- 适配器模式(Adapter)
- 适配器模式(Adapter)
- 适配器模式 Adapter Pattern
- Adapter 适配器模式
- 适配器模式(Adapter)
- Android ConstraintLayout图文并茂详解(二)
- 注册中心eureka,consul,zooKeeper,etcd选型
- RabbitMQ消息队列(二):”Hello, World“
- 06.node+mongodb 基本CRUD
- js设置全局变量 ajax中赋值
- 适配器模式(adapter)
- 并发 并行 同步 异步 多线程的区别
- 在windows下使用Charles对移动终端抓包(https请求)
- Spring Boot 知识总结贴
- React学习笔记实战1:todo列表
- BZOJ3367 带权并查集
- 神奇DP [HNOI2004] 打砖块
- 服务器与客户端模型SIGPIPIE信号
- 系统学习深度学习(四十二)--FPN