Java设计模式之适配器模式
1. 适配器模式概述
1.1 适配器定义
将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能在一起工作的那些类可以一起工作。《设计模式:可复用面向对象软件的基础》
1.2 适配器分类
适配器模式分为3中
1.类适配器模式:通过适配器类继承源类,实现目标类,将源类转换为目标类输出。
2.对象适配器模式:通过适配器类构造方法注入源类,实现目标类,将源类转换为目标类输出。
3.默认适配器模式
总结:无论使用那一种方式,适配器就是一个目的,将源类转换为目标类
2. 适配器模式实现
2.1 类适配器模
/**
* 创建源类
* 输出220V电压
*
* @author 20023262
* @date 2020/12/4
* @since 1.0
*/
public class PowerSource {
private int output = 220;
public int output220V() {
System.out.println("电源输出电压:" + output);
return output;
}
}
/**
* 目标类
* 输出5V电压
*
* @author 20023262
* @date 2020/12/4
* @since 1.0
*/
public interface PowerTarget {
/**
* 输出5v电压
*/
int output5V();
}
/**
* 类适配器
* 电压转换适配器
*
* @author 20023262
* @date 2020/12/4
* @since 1.0
*/
public class PowerAdapter extends PowerSource implements PowerTarget {
@Override
public int output5V() {
int output = output220V();
System.out.println("电源适配器开始工作,源电压:" + output);
output = output / 44;
System.out.println("电源适配器开始工作,适配电压:" + output);
return output;
}
}
/**
* 适配器测试类
* 源类PowerSource是220V,目标类PowerTarget是5V
* 现在在不改变目标类PowerTarget对外输出5V的情况下,将220V转换
* 所以新增适配器类,将220V转换为5V
* <p>
* 下游所以系统接收的都是5V,为了不改造所有下游系统,220V又不能直接调用,只能新写一个类将220V转换为5V,
* 这个类就是适配器类,适配器类继承源目标类,实现目标类即可,调用的时候直接调用适配器类,而无需改造下游系统
*
* @author 20023262
* @date 2020/12/4
* @since 1.0
*/
public class PowerAdapterTest {
/**
*
*/
@Test
public void powerAdapterTest() {
PowerAdapter powerAdapter = new PowerAdapter();
powerAdapter.output5V();
}
}
2.2 对象适配器模
/**
* 对象适配器
* 是将源对象通过构造方法注入进来
* 无论使用哪种方式目的只有一个,就是将源类转换为目标类输出
*
* @author 20023262
* @date 2020/12/4
* @since 1.0
*/
public class PowerAdapter implements PowerTarget {
// 将源对象引入
private PowerSource powerSource;
public PowerAdapter(PowerSource powerSource) {
this.powerSource = powerSource;
}
@Override
public int output5V() {
int output = powerSource.output220V();
System.out.println("电源适配器开始工作,源电压:" + output);
output = output / 44;
System.out.println("电源适配器开始工作,适配电压:" + output);
return output;
}
}