【适配器模式中主要角色】
目标(Target)角色:定义客户端使用的与特定领域相关的接口,这也就是我们所期待得到的
源(Adaptee)角色:需要进行适配的接口
适配器(Adapter)角色:对Adaptee的接口与Target接口进行适配;适配器是本模式的核心,适配器把源接口转换成目标接口,此角色为具体类。
目标(Target)角色:定义客户端使用的与特定领域相关的接口,这也就是我们所期待得到的
源(Adaptee)角色:需要进行适配的接口
适配器(Adapter)角色:对Adaptee的接口与Target接口进行适配;适配器是本模式的核心,适配器把源接口转换成目标接口,此角色为具体类。
其实也就是你家墙上有一个两口的插座(Adaptee),但你买了一个电风扇(Target)需要三个口的,这个时候你就需要一个插排(Adapter)。
【类适配器模式PHP示例】
类适配器使用的是继承
类适配器使用的是继承
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
|
/**
* 目标角色
*/
interface
Target {
/**
* 源类也有的方法1
*/
public
function
sampleMethod1();
/**
* 源类没有的方法2
*/
public
function
sampleMethod2();
}
/**
* 源角色
*/
class
Adaptee {
/**
* 源类含有的方法
*/
public
function
sampleMethod1() {
echo
'Adaptee sampleMethod1 <br />'
;
}
}
/**
* 类适配器角色
*/
class
Adapter
extends
Adaptee
implements
Target {
/**
* 源类中没有sampleMethod2方法,在此补充
*/
public
function
sampleMethod2() {
echo
'Adapter sampleMethod2 <br />'
;
}
}
class
Client {
/**
* Main program.
*/
public
static
function
main() {
$adapter
=
new
Adapter();
$adapter
->sampleMethod1();
$adapter
->sampleMethod2();
}
}
|
【对象适配器模式PHP示例】
对象适配器使用的是委派
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
|
/**
* 目标角色
*/
interface
Target {
/**
* 源类也有的方法1
*/
public
function
sampleMethod1();
/**
* 源类没有的方法2
*/
public
function
sampleMethod2();
}
/**
* 源角色
*/
class
Adaptee {
/**
* 源类含有的方法
*/
public
function
sampleMethod1() {
echo
'Adaptee sampleMethod1 <br />'
;
}
}
/**
* 类适配器角色
*/
class
Adapter
implements
Target {
private
$_adaptee
;
public
function
__construct(Adaptee
$adaptee
) {
$this
->_adaptee =
$adaptee
;
}
/**
* 委派调用Adaptee的sampleMethod1方法
*/
public
function
sampleMethod1() {
$this
->_adaptee->sampleMethod1();
}
/**
* 源类中没有sampleMethod2方法,在此补充
*/
public
function
sampleMethod2() {
echo
'Adapter sampleMethod2 <br />'
;
}
}
class
Client {
/**
* Main program.
*/
public
static
function
main() {
$adaptee
=
new
Adaptee();
$adapter
=
new
Adapter(
$adaptee
);
$adapter
->sampleMethod1();
$adapter
->sampleMethod2();
}
}
|
类适配器采用“多继承”的实现方式,带来了不良的高耦合,所以一般不推荐使用。对象适配器采用“对象组合”的方式,更符合松耦合精神。
这里还有一篇对对象适配器的很好的说明可以看一下http://www.knowsky.com/890188.html。