适配器模式

适配器模式

  • 定义
    将一个类转换成客户希望看到的另一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。简单来说:你现在有一个A的对象,但是现在需要B接口的对象,通过适配器模式可将A伪装成一个B的对象,达到目的,A的对象、B接口在功能上要类似。核心便是转化二字。
  • 角色
    1. 目标接口
    2. 适配器
    3. 被适配接口
  • 分类
    有对象适配器和类适配器两种。
    1. 类适配器是采用多重继承的方式,使适配器同事继承目标接口和被适配接口。
    2. 对象适配器则是适配器实现目标接口,同时拥有一个被适配接口的对象,当client需要调用目标接口方法时,则通过调用被适配接口的对象来完成任务。

代码示例

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
76
77
78
79
80
81
82
/**
* 目标接口
* @author sky
*
*/
public interface GoodStudent {

public void hardWorking();

}

/**
* 被适配者接口
* @author sky
*
*/
public interface BadStudent {

public void lazyWorking();
}

/**
* 被适配子类
* @author sky
*
*/
public class Jon implements BadStudent {

@Override
public void lazyWorking() {
System.out.println("学习一分钟");

}

}

/**
* 适配器类,将一个坏学生,包装成好学生
* @author sky
*
*/
public class Adapter implements GoodStudent {

private BadStudent badStudent;

public Adapter(BadStudent bStudent){
badStudent = bStudent;
}

@Override
public void hardWorking() {
for (int i = 0; i < 10; i++) { //坏学生要付出10倍的努力
badStudent.lazyWorking();
}
}

}

/**
* 测试类
* @author sky
*
*/
public class Test {

private GoodStudent goodStudent;

public Test(GoodStudent gStudent){
goodStudent = gStudent;
}

public void testWork(){
goodStudent.hardWorking();
}

public static void main(String[] args) {
BadStudent badStudent = new Jon();
Adapter adapter = new Adapter(badStudent);
Test test = new Test(adapter);
test.testWork();
}
}