↑↑↑ 欢迎关注,分享更多 IT 技术
注:本笔记为 公司内部技术小组持续学习 2 年多时间 + 个人整理不下 5 次的结果产出。
目录
51 | 适配器模式:代理、适配器、桥接、装饰,这四个模式有何区别?
51 | 适配器模式:代理、适配器、桥接、装饰,这四个模式有何区别?
适配器模式的原理与实现
-
定义
-
适配器模式(Adapter Design Pattern)
-
将不兼容的接口转换为可兼容的接口,让原本由接口不兼容而不能一起工作的类可以一起工作。
-
-
实现方式:
-
类适配器
类适配器使用继承关系来实现
-
对象适配器。示例代码如下:
对象适配器使用组合关系来实现
-
-
代码实现
-
// 类适配器: 基于继承 public interface ITarget { void f1(); void f2(); void fc(); } public class Adaptee { public void fa() { //... } public void fb() { //... } public void fc() { //... } } public class Adaptor extends Adaptee implements ITarget { public void f1() { super.fa(); } public void f2() { //...重新实现f2()... } // 这里fc()不需要实现,直接继承自Adaptee,这是跟对象适配器最大的不同点 } // 对象适配器:基于组合 public interface ITarget { void f1(); void f2(); void fc(); } public class Adaptee { public void fa() { //... } public void fb() { //... } public void fc() { //... } } public class Adaptor implements ITarget { private Adaptee adaptee; public Adaptor(Adaptee adaptee) { this.adaptee = adaptee; } public void f1() { adaptee.fa(); //委托给Adaptee } public void f2() { //...重新实现f2()... } public void fc() { adaptee.fc(); } }
-
适配器模式应用场景总结
-
适配器模式可以看作一种“补偿模式”,用来补救设计上的缺陷。
1. 封装有缺陷的接口设计
-
为了隔离设计上的缺陷,我们希望对外部系统提供的接口进行二次封装,抽象出更好的接口设计。
-
代码示例
-
public class CD { //这个类来自外部sdk,我们无权修改它的代码 //... public static void staticFunction1() { //... } public void uglyNamingFunction2() { //... } public void tooManyParamsFunction3(int paramA, int paramB, ...) { //... } public void lowPerformanceFunction4() { //... } } // 使用适配器模式进行重构 public class ITarget { void function1(); void function2(); void fucntion3(ParamsWrapperDefinition paramsWrapper); void function4(); //... } // 注意:适配器类的命名不一定非得末尾带Adaptor public class CDAdaptor extends CD implements ITarget { //... public void function1() { super.staticFunction1(); } public void function2() { super.uglyNamingFucntion2(); } public void function3(ParamsWrapperDefinition paramsWrapper) { super.tooManyParamsFunction3(paramsWrapper.getParamA(), ...); } public void function4() { //...reimplement it... } }
-
2. 统一多个类的接口设计
-
某个功能的实现依赖多个外部系统(或类)。通过适配器模式,将它们的接口适配为统一的接口定义。
-
代码示例
-
public class ASensitiveWordsFilter { // A敏感词过滤系统提供的接口 //text是原始文本,函数输出用***替换敏感词之后的文本 public String filterSexyWords(String text) { // ... } public String filterPoliticalWords(String text) { // ... } } public class BSensitiveWordsFilter { // B敏感词过滤系统提供的接口 public String filter(String text) { //... } } public class CSensitiveWordsFilter { // C敏感词过滤系统提供的接口 public String filter(String text, String mask) { //... } } // 未使用适配器模式之前的代码:代码的可测试性、扩展性不好 public class RiskManagement { private ASensitiveWordsFilter aFilter = new ASensitiveWordsFilter(); private BSensitiveWordsFilter bFilter = new BSensitiveWordsFilter(); private CSensitiveWordsFilter cFilter = new CSensitiveWordsFilter(); public String filterSensitiveWords(String text) { String maskedText = aFilter.filterSexyWords(text); maskedText = aFilter.filterPoliticalWords(maskedText); maskedText = bFilter.filter(maskedText); maskedText = cFilter.filter(maskedText, "***"); return maskedText; } } // 使用适配器模式进行改造 public interface ISensitiveWordsFilter { // 统一接口定义 String filter(String text); } public class ASensitiveWordsFilterAdaptor implements ISensitiveWordsFilter { private ASensitiveWordsFilter aFilter; public String filter(String text) { String maskedText = aFilter.filterSexyWords(text); maskedText = aFilter.filterPoliticalWords(maskedText); return maskedText; } } //...省略BSensitiveWordsFilterAdaptor、CSensitiveWordsFilterAdaptor... // 扩展性更好,更加符合开闭原则,如果添加一个新的敏感词过滤系统, // 这个类完全不需要改动;而且基于接口而非实现编程,代码的可测试性更好。 public class RiskManagement { private List<ISensitiveWordsFilter> filters = new ArrayList<>(); public void addSensitiveWordsFilter(ISensitiveWordsFilter filter) { filters.add(filter); } public String filterSensitiveWords(String text) { String maskedText = text; for (ISensitiveWordsFilter filter : filters) { maskedText = filter.filter(maskedText); } return maskedText; } }
-
3. 替换依赖的外部系统
-
当我们把项目中依赖的一个外部系统替换为另一个外部系统的时候,利用适配器模式,可以减少对代码的改动。
-
代码示例
-
// 外部系统A public interface IA { //... void fa(); } public class A implements IA { //... public void fa() { //... } } // 在我们的项目中,外部系统A的使用示例 public class Demo { private IA a; public Demo(IA a) { this.a = a; } //... } Demo d = new Demo(new A()); // 将外部系统A替换成外部系统B public class BAdaptor implemnts IA { private B b; public BAdaptor(B b) { this.b= b; } public void fa() { //... b.fb(); } } // 借助BAdaptor,Demo的代码中,调用IA接口的地方都无需改动, // 只需要将BAdaptor如下注入到Demo即可。 Demo d = new Demo(new BAdaptor(new B()));
-
4. 兼容老版本接口
-
在 JDK1.0 升级到 JDK2.0 时。我们可以暂时保留 Enumeration 类,并将其实现替换为直接调用 Itertor。
-
代码示例
-
public class Collections { public static Emueration emumeration(final Collection c) { return new Enumeration() { Iterator i = c.iterator(); public boolean hasMoreElments() { return i.hashNext(); } public Object nextElement() { return i.next(): } } } }
-
5. 适配不同格式的数据
-
它还可以用在不同格式的数据之间的适配。
-
代码示例
-
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
-
适配器模式在 Java 日志中的应用
-
Slf4j,它相当于 JDBC 规范,提供了一套打印日志的统一接口规范。不过,它只是定义了接口,并没有提供具体实现,需要配合其他日志框架(log4j、logback……)来使用。
-
它不仅提供了统一的接口定义,不提供了针对不同日志框架的适配器。对不同日志框架的接口进行二次封装,适配成统一的 Slf4j 接口定义。
-
代码如下:
-
// slf4j统一的接口定义 package org.slf4j; public interface Logger { public boolean isTraceEnabled(); public void trace(String msg); public void trace(String format, Object arg); public void trace(String format, Object arg1, Object arg2); public void trace(String format, Object[] argArray); public void trace(String msg, Throwable t); public boolean isDebugEnabled(); public void debug(String msg); public void debug(String format, Object arg); public void debug(String format, Object arg1, Object arg2) public void debug(String format, Object[] argArray) public void debug(String msg, Throwable t); //...省略info、warn、error等一堆接口 } // log4j日志框架的适配器 // Log4jLoggerAdapter实现了LocationAwareLogger接口, // 其中LocationAwareLogger继承自Logger接口, // 也就相当于Log4jLoggerAdapter实现了Logger接口。 package org.slf4j.impl; public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable { final transient org.apache.log4j.Logger logger; // log4j public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public void debug(String msg) { logger.log(FQCN, Level.DEBUG, msg, null); } public void debug(String format, Object arg) { if (logger.isDebugEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } public void debug(String format, Object arg1, Object arg2) { if (logger.isDebugEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } public void debug(String format, Object[] argArray) { if (logger.isDebugEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } public void debug(String msg, Throwable t) { logger.log(FQCN, Level.DEBUG, msg, t); } //...省略一堆接口的实现... }
-
代码、桥接、装饰器、适配器 4 种设计模式的区别
-
代理模式:代理模式在不改变原始类接口的条件下,为原始类定义一个代理类。主要目标是实现非业务性需求,而非业务增强功能,这是它跟装饰器模式最大的不同。
-
桥接模式:桥接模式的目的是将接口和实现分离,从而让它们可以较为容易、也相对独立地加以改变。
-
装饰器模式:装饰者模式在不改变原始类接口的情况下,对原始类功能进行增强。并且支持多个装饰器的嵌套使用。
-
适配器模式:适配器模式是一种事后的补救策略。适配器提供跟原始类不同的接口,而代理模式、装饰器模式提供的都是跟原始类相同的接口。
重点回顾
-
适配器模式是用来做适配,它将不兼容的接口转换为可兼容的接口,让原本由于接口不兼容而不能在一起工作的类可以一起工作。
-
适配器模式有两种实现方式:
-
类适配器
类适配器使用继承关系来实现
-
对象适配器
对象适配器使用组合关系来实现。
-
-
一般来说,适配器模式可以看作一种“补偿模式”,用来补救设计上的缺陷。
-
应用场景
-
封装有缺陷的接口设计
-
统一多个类的接口设计
-
替换依赖的外部系统
-
兼容老版本接口
-
适配不同格式的数据
-
参考地址:https://time.geekbang.org/column/intro/100039001
欢迎大家点赞、关注!!!持续分享更多 IT 技术 干货