适配器模式
来源:互联网 发布:javascript简单游戏 编辑:程序博客网 时间:2024/06/04 19:14
定义
Convert thr interface of a class into another interface clients expect. Adapter lets classes work together taht couldn't otherwise because of incompatible interfaces.
(将一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作)
通用类图:
适用场景:
注意事项:
适配器模式不是为了解决还处在开发阶段的问题,而是解决正在服役的项目问题。项目一定要遵守依赖倒置原则和里氏替换原则,否则即使在适合使用适配器的场合下,也会带来非常大的改造。优点:
- 适配器模式可以让两个没有任何关系的类在一起运行,只要适配器这个角色就能够搞定他们就成。
- 增加了类的透明性。
- 提高了类的复用度。
- 灵活性非常好。
例子:
我们现在有两个系统,都有员工对象,其中系统一:
import java.util.HashMap;import java.util.Map;/** * Created by dushangkui on 2017/6/12. */public class Employee { private String id; private String name; private Map<String,Object> info; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, Object> getInfo() { if(info==null){ info = new HashMap<String, Object>(); } return info; } public void setInfo(Map<String, Object> info) { this.info = info; }}
我们把地址等信息存放在info字段中,但是另一个系统中的员工类不完全对应:
public class EmplyeeAdapter { private String code; private String name; private String address; public EmplyeeAdapter(Employee employee){ this.code=employee.getId(); this.name=employee.getName(); this.address= (String) employee.getInfo().get("address"); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "EmplyeeAdapter{" + "code='" + code + '\'' + ", name='" + name + '\'' + ", address='" + address + '\'' + '}'; }}场景类:
public class Client { public static void main(String[] args) { Employee employee = new Employee(); employee.setId("001"); employee.setName("张三"); employee.getInfo().put("address","江苏省南京市玄武区"); EmplyeeAdapter adapter = new EmplyeeAdapter(employee); System.out.println(adapter); }}
阅读全文
1 0
- 适配器及适配器模式
- 适配器及适配器模式
- 适配器模式(类适配器)
- 适配器模式(默认适配器)
- 适配器模式(对象适配器)
- 适配器模式-类适配器
- 适配器模式-对象适配器
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- xcode8由于权限问题导致崩溃
- rsa+aes非对称加密实例(两对公私钥)
- 《DeepWalk: Online Learning of Social Representations》学习笔记
- RBAC总结
- SSD源码解读1~~~~~~~~~~ssd_pascal.py
- 适配器模式
- 在ssm项目中使用redisTemplate
- 一名 40 岁“老”程序员的反思
- tr
- 转换字符串格式为字符+连续出现的次数
- 极简单片机开发
- ftp(vsftp) 在Cortex-A9 ARM CPU s5p4418上的移植
- 枚举类和常量
- install php7 mysql5.6 apache2.4 in centos 6 or 7