适配器就是一种适配中间件,它存在于不匹配的二者之间,用于连接二者,将不匹配变得匹配。
场景:电脑读取内存卡中的内容,内存卡是没有办法直接插在电脑的USB接口上,那就不需要一个转换器。
下面的例子实现了上述的功能
/** * @author liusongwei * @Title: MemoryCard * @ProjectName demohystrix * @Description: 定义一个内存卡接口 * @date 2018/12/279:15 */ public interface MemoryCard { public String novel(); }
package com.example.demohystrix.designpattern.structure.adapter; /** * @author liusongwei * @Title: MemoryCardImpl * @ProjectName demohystrix * @Description: 实现内存卡接口并编写内存中的内容 * @date 2018/12/279:18 */ public class MemoryCardImpl implements MemoryCard { @Override public String novel() { System.out.println("开始读取小说中的内容"); return "盘古开天辟地,名曰《斗鱼》"; } }
package com.example.demohystrix.designpattern.structure.adapter; /** * @author liusongwei * @Title: Computer * @ProjectName demohystrix * @Description: 定义一个电脑接口 * @date 2018/12/279:17 */ public interface Computer { public void read(); }
package com.example.demohystrix.designpattern.structure.adapter; /** * @author liusongwei * @Title: Adapter * @ProjectName demohystrix * @Description: 实现一个电脑接口的适配器,并读取内存卡中的内容 * @date 2018/12/279:20 */ public class Adapter implements Computer { private MemoryCard memoryCard; public Adapter(MemoryCard memoryCard){ this.memoryCard = memoryCard; } @Override public void read() { String str = memoryCard.novel(); System.out.println("读取的内容为:" + str); } }
package com.example.demohystrix.designpattern.structure.adapter; /** * @author liusongwei * @Title: Demo * @ProjectName demohystrix * @Description: TODO * @date 2018/12/279:22 */ public class Demo { public static void main(String[] args){ Computer computer = new Adapter(new MemoryCardImpl()); computer.read(); } }
输出内容为: