java设计模式-适配器模式

it2022-05-05  203

适配器模式的定义

1.就是把一个类接口转换成客户端所期望的另一个接口2.使原本接口不兼容的类可以一起工作

使用场景

1.已存在的类,他的方法和需求不匹配是(方法的结果相同或相似)2.不是软件设计阶段考虑的设计模式,是随着软件维护,由于不同的产品,不同的厂家造成功能类似而接口不相同情况下的解决方案

举个例子: 就好比一台笔记本的电源适配器一般都是三相的,有阴极,阳极,还有一个地极,而有些地方的插座只有,阴极和阳极,没有地级,这样笔记本就无法充电。这时候就需要一个三相转两相的转换器(适配器),就能解决该问题。正如我们这说的适配器模式一样

实现适配器模式有两种方法

类适配器对象适配器

说明: 适配器就把要适配的类转换成对应的目标类(客户端->使用方:需要的类)

类适配器模式

类图

测试类
public class Test { public static void main(String[] args) { // 使用普通类 只具有普通功能 Target concreteTarget = new ConcreteTarget(); concreteTarget.request(); // 使用被适配的类 Target adapter = new Adapter(); adapter.request(); } }
目标类
// 目标接口,或称为标准接口 public interface Target { void request(); }
被适配的类
// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类 public class Adaptee { void adapteeRequest(){ System.out.println("被适配的方法"); } }
适配器
// 类适配器 public class Adapter extends Adaptee implements Target { /** * 适配本来不符合目标的类 */ @Override public void request() { super.adapteeRequest(); } }
不需要适配的类(符合目标接口的类)
// 具体目标类,只提供普通功能 public class ConcreteTarget implements Target { @Override public void request() { System.out.println("普通类,具有普通功能"); } }

测试结果

普通类,具有普通功能 被适配的方法


对象适配器

注意: 对象适配器与类适配器最主要的区别在于,对象适配器是通过组合的方式去做的,而不是通过继承的方式去实现的

对象适配器
// 对象适配器 public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee){ this.adaptee = adaptee; } /** * 适配本来不符合目标的类 */ @Override public void request() { System.out.println("使用对象适配器->------------"); adaptee.adapteeRequest(); } }
测试类
public class Test { public static void main(String[] args) { // 使用普通类 只具有普通功能 Target concreteTarget = new ConcreteTarget(); concreteTarget.request(); // 使用被适配的类 Target adapter = new Adapter(new Adaptee()); adapter.request(); } }
执行结果

普通类,具有普通功能 使用对象适配器->------------ 被适配的方法



最新回复(0)