什么是适配器
在设计模式中, 适配器模式 (英语: adapter pattern) 有时候也称包装样式或者包装 (wrapper). 将一个类的接口转接成用户所期待的. 一个适配使得因接口不兼容而不能在一起工作的类工作在一起, 做法是将类自己的接口包裹在一个已存在的类中.
适配器分类
适配器分为, 类适配器, 对象适配, 接口适配方式
类适配器方式采用继承方式, 对象适配方式使用构造函数传递
适配器应用场景
我们根据上面的适配器的特点的介绍中, 我们来分析下适配器模式的几类比较适用的使用场景:
1, 我们在使用第三方的类库, 或者说第三方的 API 的时候, 我们通过适配器转换来满足现有系统的使用需求.
2, 我们的旧系统与新系统进行集成的时候, 我们发现旧系统的数据无法满足新系统的需求, 那么这个时候, 我们可能需要适配器, 完成调用需求.
3, 我们在使用不同数据库之间进行数据同步.(我这里只是分析的是通过程序来说实现的时候的情况. 还有其他的很多种方式 [数据库同步]).
OutputStreamWriter: 是 Writer 的子类, 将输出的字符流变为字节流, 即: 将一个字符流的输出对象变为字节流的输出对象.
InputStreamReader: 是 Reader 的子类, 将输入的字节流变为字符流, 即: 将一个字节流的输入对象变为字符流的输入对象.
SpringMVC 适配器
适配器案例
我们就拿日本电饭煲的例子进行说明, 日本电饭煲电源接口标准是 110V 电压, 而中国标准电压接口是 220V, 所以要想在中国用日本电饭煲, 需要一个电源转换器.
定义日本和中国两种接口及其实现
我们先定义日本 220V 电源接口和实现.
- package com.example.demo.adapter;
- /**
- * 中国 220V 电源接口
- */
- public interface China220VInterface {
- public void connect();
- }
- package com.example.demo.adapter;
- /**
- * 中国电压 220V 电源
- */
- public class China220VInterfaceImpl implements China220VInterface {
- @Override
- public void connect() {
- System.out.println("中国 220V 电源开始工作...");
- }
- }
- package com.example.demo.adapter;
- /**
- * 日本 110V 电压接口
- */
- public interface JP110VInterface {
- /**
- * 电源接口
- */
- void connect();
- }
- package com.example.demo.adapter;
- /**
- * 日本 110V 电源接口实现类
- */
- public class JP110VInterfaceImpl implements JP110VInterface {
- @Override
- public void connect() {
- System.out.println("日本 110V 电源接口开始工作...");
- }
- }
- package com.example.demo.adapter;
- /**
- * 电饭煲接口
- */
- public class ElectricCooker {
- private JP110VInterface ap110VInterface;
- public ElectricCooker(JP110VInterface ap110VInterface){
- this.ap110VInterface=ap110VInterface;
- }
- public void work(){
- // 电源方法执行
- ap110VInterface.connect();
- System.out.println("电饭煲开始工作...");
- }
- }
- package com.example.demo.adapter;
- /**
- * 电源适配器
- */
- public class PowerAdapter implements JP110VInterface {
- private China220VInterface china220VInterface;
- public PowerAdapter(China220VInterface china220VInterface){
- this.china220VInterface=china220VInterface;
- }
- @Override
- public void connect() {
- china220VInterface.connect();
- }
- }
- package com.example.demo.adapter;
- /**
- * 测试
- */
- public class AdapterTest {
- public static void main(String[] args) {
- //220V 电源接口
- China220VInterface china220VInterface=new China220VInterfaceImpl();
- // 适配器接口
- PowerAdapter powerAdapter=new PowerAdapter(china220VInterface);
- // 电饭煲工作
- ElectricCooker electricCooker=new ElectricCooker(powerAdapter);
- electricCooker.work();
- }
- }
来源: http://www.bubuko.com/infodetail-3053223.html