什么是适配器模式
- 将某个类的接口转换为客户端期望的另一个接口表示, 主要目的是兼容性, 让原本因接口不匹配不能一起工作的两个类可以协同工作。
- 适配器模式属于结构型模式
- 适配器模式分为三类, 分别是类适配器模式、对象适配器模式、接口适配器模式
电压问题
插座的电压是220V, 手机充电器要求的是5V, 充电器就相当于适配器, 将220V交流电转为5V直流电
Java
- 类适配器模式
220V插座
// 被适配的220v插座
public class Voltage220V {
//输出220v电压
public int output220V(){
return 220;
}
}
适配器接口
//适配接口
public interface IVoltage5V {
public int output5V();
}
适配器接口实现类
//适配器类
public class VoltageAdapter extends Voltage220V implements IVoltage5V {
//220V转5V
@Override
public int output5V() {
int srcV = output220V();
int dstV = srcV / 44;
return dstV;
}
}
手机通过适配器充电
public class Phone {
//充电
public void charging(IVoltage5V iVoltage5V){
if(iVoltage5V.output5V() == 5){
System.out.println("5v, 可以充电.....");
}else {
System.out.println("非5v, 无法充电.....");
}
}
}
Test.class
//测试给手机充电
public class Test {
public static void main(String[] args) {
//给手机充电
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
- 对象适配器模式
VoltageAdapter.class
//适配器类
public class VoltageAdapter implements IVoltage5V {
private Voltage220V voltage220V;
//通过构造器, 传入一个Voltage220V实例
public VoltageAdapter(Voltage220V voltage220V) {
this.voltage220V = voltage220V;
}
@Override
public int output5V() {
int dstV = 0;
if(voltage220V != null){
int srcV = voltage220V.output220V();
dstV = srcV / 44;
}
return dstV;
}
}
Test.class
//测试手机充电
public class Test {
public static void main(String[] args) {
Phone phone = new Phone();
phone.charging(new VoltageAdapter(new Voltage220V()));
}
}
- 接口适配器模式
当不需要全部实现接口提供的方法时,可以设计一个抽象类实现接口,并为该接口中每个方法提供一个默认实现(空方法),那么该抽象类的子类可有选择的覆盖父类的某些方法来实现需求。
接口
public interface Interface {
void m1();
void m2();
void m3();
}
顶一个抽象类,对接口中的方法进行默认实现
public abstract class AbsAdapter implements Interface {
@Override
public void m1() {
}
@Override
public void m2() {
}
@Override
public void m3() {
}
}
public class Test {
public static void main(String[] args) {
//这里只需要覆盖我们需要使用的接口方法
AbsAdapter absAdapter = new AbsAdapter() {
@Override
public void m1() {
}
};
absAdapter.m1();
}
}
网友评论