适配器模式(Adapter)
运用于在现有几套不同的组件,互相间的接口定义不一致,又期望让他们可以协同工作,可以通过实现一套适配器,让本身无法兼容的组件可以协同工作了
mybatis中兼容了很多日志组件,不同的日志组件中又定义了不同的日志级别,因此mybatis定义了一套标准的日志级别,然后针对不同的日志组件,开发一套不同的适配器,让兼容的日志组件得以对应到mybatis的日志级别上
举个例子,你买了一个欧版水货数码产品,充电器的插头和国内的国标接口不一样,所以我们需要买一个转换头(适配器),让本来不能在国标插座上充电的设备能正常充电了
接口适配器
- 接口一
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 0:51
*/
public interface InterfaceA {
String saySomething (String xxx);
}
- 接口一实现
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 0:57
*/
public class AImpl implements InterfaceA {
@Override
public String saySomething (String xxx) {
return "1234" + xxx;
}
}
- 接口二
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 0:55
*/
public interface InterfaceB {
Long printLong (Long number);
}
- 适配器
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 0:56
*/
public class Adapter extends AImpl implements InterfaceB {
@Override
public Long printLong (Long number) {
//适配过程
return number + Long.parseLong(saySomething("555"));
}
}
- 测试
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 0:59
*/
public class Main {
public static void main (String[] args) {
Adapter adapter = new Adapter();
Long aLong = adapter.printLong(1L);
System.out.println(aLong);
}
}
类适配器
- 接口定义
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 0:51
*/
public interface InterfaceA {
String saySomething (String xxx);
}
- 接口实现
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 1:02
*/
public class AImpl implements InterfaceA {
private Person person;
public AImpl (Person person) {
this.person = person;
}
@Override
public String saySomething (String xxx) {
return this.person.print();
}
}
- 需要适配对象
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 1:02
*/
public class Person {
public String print () {
System.out.println("od");
return "sxxx";
}
}
- 将对象传入进行适配
/**
* @author Xiaoyingge
* @description
* @date 2020/4/27 1:04
*/
public class Main {
public static void main (String[] args) {
AImpl a = new AImpl(new Person());
a.saySomething("ss");
}
}