在软件系统中,由于应用环境的变化,常常需要将“一些现存的对象”放在新的环境中应用,但是新环境要求的接口是这些现存对象所不满足的。
如何应对这种“迁移的变化”?如何既能利用现有对象的良好实现,同时又能满足新的应用环境所要求的接口?
意图:
将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
出自:《设计模式》GoF
Adapter模式的几个要点:
1、Adapter模式主要应用于“希望复用一些现存的类,但是接口又与复用的环境要求不一致的情况”,在遗留代码复用、类库迁移等方面非常有用。
2、GoF23定义了两种Adapter模式的实现结构:类适配器和对象适配器.对象适配器采用“对象组合”的方式,更符合松耦合精神。一般推荐对象适配器.
3、Adapter模式可以实现的非常灵活,不必拘泥于GoF23中定义的两种结构。例如,完全可以将Adapter模式中的“现存对象”作为新的接口方法参数,来达到适配的目的。
4、Adapter模式本身要求我们尽可能地使用“面向接口的编程”风格,这样才能在后期很方便地适配。
稳定部分:
1
using System;
2
3
namespace Adapter
4
{
5
/// <summary>
6
/// Istack 的摘要说明。
7
/// </summary>
8
interface Istack // 客户期望的接口,这里被适配的对象是一个ArrayList对象
9
{
10
void Push(object item);
11
void Pop();
12
object Peek();
13
}
14
}
15

2

3

4

5

6

7

8

9

10

11

12

13

14

15

变化部分:
1
using System;
2
using System.Collections;
3
namespace Adapter
4
{
5
/// <summary>
6
/// Adapter 的摘要说明。
7
/// </summary>
8
//对象适配器(推荐使用)
9
class AdapterA: Istack //适配对象
10
{
11
ArrayList adpatee = new ArrayList(); //被适配的对象
12
13
public AdapterA()
14
{
15
adpatee.Add("1");
16
adpatee.Add("2");
17
adpatee.Add("3");
18
}
19
20
public void Push(object item)
21
{
22
adpatee.Add(item);
23
}
24
25
public void Pop()
26
{
27
adpatee.RemoveAt(adpatee.Count - 1);
28
}
29
30
public object Peek()
31
{
32
return adpatee[adpatee.Count - 1];
33
}
34
}
35
36
//类适配器
37
class AdapterB: ArrayList,Istack //适配对象
38
{
39
public AdapterB()
40
{
41
this.Add("1");
42
this.Add("2");
43
this.Add("3");
44
}
45
46
public void Push(object item)
47
{
48
this.Add(item);
49
}
50
51
public void Pop()
52
{
53
this.RemoveAt(this.Count - 1);
54
}
55
56
public object Peek()
57
{
58
return this[this.Count - 1];
59
}
60
}
61
}
62

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

主程序:
1
using System;
2
3
namespace Adapter
4
{
5
/// <summary>
6
/// Class1 的摘要说明。
7
/// </summary>
8
class Class1
9
{
10
/// <summary>
11
/// 应用程序的主入口点。
12
/// </summary>
13
[STAThread]
14
static void Main(string[] args)
15
{
16
string item ="tt";
17
AdapterA a = new AdapterA();
18
19
a.Push(item);
20
a.Pop();
21
Console.Write(a.Peek());
22
23
AdapterB b = new AdapterB();
24
b.Push(item);
25
b.Pop();
26
Console.Write(b.Peek());
27
Console.ReadLine();
28
29
}
30
}
31
}
32

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
