Hongbo

Oct 13, 2023

浅谈适配器模式

写在前头:希望你了解到的不仅是模式,而学会用OOP的眼光分析问题,解决问题

关键字:连接

描述:适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。适配器不是在详细设计时添加的,而是解决正在服役的项目的问题。

原则:OFC,单一职责

区别:与代理模式的区别

示例:充电口转换

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//美国工具接口
public interface USATool {
// 工具运行
public void run();

}

//美国充电器类
public class USACharger implements USATool {

@Override
public void run() {
System.out.println("insert to usa interface success!");
}

}

//中国工具接口
public interface ChinaTool {
// 工具运行
public void run(String type);

}

//适配器器类(转换中国接口)
public class AdapterChager implements ChinaTool {
//能转接美国充电口
private USATool usaChager;

@Override
public void run(String type) {
if(type.equalsIgnoreCase("usatype")) {
usaChager =new USACharger();
usaChager.run();
}else {

System.out.println("At present, can't connect to this interface!");
}

}
}

//中国充电器类
public class ChinaCharger implements ChinaTool {
//可以连接适配器
private ChinaTool adapter;

@Override
public void run(String type) {
//中国接口,无需使用适配器
if(type.equalsIgnoreCase("chinatype")) {
System.out.println("insert to china interface success!");
//美国接口,需要使用适配器
}else if(type.equalsIgnoreCase("usatype")) {
//这里相当于 责任托付,具体连接交给适配器去做
adapter = new AdapterChager();
adapter.run(type);
//不能识别的接口
}else {
System.out.println("At present, can't connect to this interface!");
}
}

//test
public static void main(String[] args) {

ChinaCharger charger= new ChinaCharger();

charger.run("chinatype");

charger.run("usatype");

charger.run("othertype");
}
}
OLDER > < NEWER