将一个类的接口转换成用户希望得到的另一种接口。它使原本不相容的接口得以协同工作。
1、类适配器
package com.strife.pattern.adapter;
/**
* 类适配器模式
*
* @author mengzhenghao
* @date 2022/5/29
*/
public class ClassAdapter {
public static void main(String[] args) {
IVoltage5V voltage5V = new VoltageAdapter();
Phone phone = new Phone();
phone.charge(voltage5V);
}
}
/**
* 220V电压(被适配的类)
*/
class Voltage220V {
public int output220V() {
int src = 220;
System.out.println("电压" + src + "伏");
return src;
}
}
/**
* 5V电压(适配接口)
*/
interface IVoltage5V {
int output5V();
}
/**
* 适配器类
*/
class VoltageAdapter extends Voltage220V implements IVoltage5V {
@Override
public int output5V() {
int src = output220V();
System.out.println("将220V电压转换为5V");
//转成5V
return src / 44;
}
}
/**
* 使用者
*/
class Phone {
public void charge(IVoltage5V voltage5V) {
if (voltage5V.output5V() == 5) {
System.out.println("电压是5V,可以充电");
} else if (voltage5V.output5V() > 5) {
System.out.println("电压是大于5V,不可以充电");
}
}
}
2、对象适配器
package com.strife.pattern.adapter;
/**
* 对象适配器
*
* @author mengzhenghao
* @date 2022/5/29
*/
public class ObjectAdapter {
public static void main(String[] args) {
Voltage220V1 voltage220V1 = new Voltage220V1();
IVoltage5V voltage5V = new VoltageAdapter1(voltage220V1);
Phone1 phone = new Phone1();
phone.charge(voltage5V);
}
}
/**
* 220V电压(被适配的类)
*/
class Voltage220V1 {
public int output220V() {
int src = 220;
System.out.println("电压" + src + "伏");
return src;
}
}
/**
* 5V电压(适配接口)
*/
interface IVoltage5V1 {
int output5V();
}
/**
* 适配器类
*/
class VoltageAdapter1 implements IVoltage5V {
/** 聚合被适配类 */
private final Voltage220V1 voltage220V1;
public VoltageAdapter1(Voltage220V1 voltage220V1) {
this.voltage220V1 = voltage220V1;
}
@Override
public int output5V() {
int src = voltage220V1.output220V();
System.out.println("将220V电压转换为5V");
//转成5V
return src / 44;
}
}
/**
* 使用者
*/
class Phone1 {
public void charge(IVoltage5V voltage5V) {
if (voltage5V.output5V() == 5) {
System.out.println("电压是5V,可以充电");
} else if (voltage5V.output5V() > 5) {
System.out.println("电压是大于5V,不可以充电");
}
}
}
3、接口适配器模式(缺省适配器模式)
使用情形:当不需要全部实现接口提供的方法时,可以先设计一个抽象类实现接口,并未该接口中每个方法提供一个默认实现(空方法),那么该抽象类的子类可以有选择的覆盖父类的某些方法来实现需求。
package com.strife.pattern.adapter;
/**
* 接口适配器
*
* @author mengzhenghao
* @date 2022/5/29
*/
public class InterfaceAdapter {
public static void main(String[] args) {
final AbstractAdapter adapter = new AbstractAdapter() {
@Override
public void method1() {
System.out.println("使用了method1方法");
}
};
adapter.method1();
}
}
interface InterfaceA {
void method1();
void method2();
void method3();
void method4();
}
abstract class AbstractAdapter implements InterfaceA {
@Override
public void method1() {}
@Override
public void method2() {}
@Override
public void method3() {}
@Override
public void method4() {}
}