适配器模式

适配器模式

属于结构型模式

适配器模式将两个不兼容的类通过适配器能够做到兼容;
用户调用适配器转化后的接口方法, 适配器再调用被适配者的接口方法;
用户只要关心适配器暴露的接口方法

为什么使用适配器模式

现实中,存在很多的适配器, 比如电源适配器; 让原本不能直接兼容的两个对象, 通过适配器进行兼容

使用适配器模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 被适配者, 比如插座 交流220V
public class Adaptee {
public int output(){
return 220;
}
}

// 适配器 电源适配器 转化成低压直流电
public class Adapter {
void input(Adaptee adaptee){
System.out.println("输入电压: "+adaptee.output());
}

int output(){
System.out.println("输出电压: "+5);
return 5;
}
}

// 使用者 需要充电的电池
public class Battery {
public void charging(Adapter adapter){
if (adapter.output()==5){
System.out.println("充电");
}else{
System.out.println("不适配");
}
}
}