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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

/**
* 普通媒体接口
*/

interface MediaInterface
{
public function play($file='');
}


/**
* 高级媒体接口
*/
interface MediaAdvanceInterface
{
public function playMp4($file='');
public function playWma($file='');
}

/**
* 高级播放器适配器
*/
class Adapter
{
private $_advancePlayerInstance;

private $_type = '';

public function __construct($type='')
{
switch ($type) {
case 'mp4':
$this->_advancePlayerInstance = new AdvanceMp4Player();
break;
case 'wma':
$this->_advancePlayerInstance = new AdvanceWmaPlayer();
break;

default:
throw new Exception("$type is not supported", 400);
break;
}
$this->_type = $type;
}

public function play($file='')
{
switch ($this->_type) {
case 'mp4':
$this->_advancePlayerInstance->playMp4($file);
break;
case 'wma':
$this->_advancePlayerInstance->playWma($file);
break;
default:
break;
}
}
}

/**
* mp4高级播放器实体
*/
class AdvanceMp4Player implements MediaAdvanceInterface
{
public function playMp4($file='')
{
echo 'AdvanceMp4Player driver playing file: ' . $file . ".mp4\n";
}

public function playWma($file='')
{
//do nothing
}
}

/**
* wma高级播放器实体
*/
class AdvanceWmaPlayer implements MediaAdvanceInterface
{
public function playMp4($file='')
{
//do nothing
}

public function playWma($file='')
{
echo 'AdvanceWmaPlayer driver playing file: ' . $file . ".wma\n";
}
}


/**
* 音频设备实体
*/
class AudioPlayer implements MediaInterface
{
public function play($file='', $type='')
{
switch ($type) {
case 'mp3':
echo 'playing file: ' . $file . ".mp3\n";
break;
case 'mp4':
$adapter = new Adapter($type);
$adapter->play($file);
break;
case 'wma':
$adapter = new Adapter($type);
$adapter->play($file);
break;

default:
throw new Exception("$type is not supported", 400);
break;
}

}
}


try {
//生产一台设备
$mp4 = new AudioPlayer();
// 播放一个mp3
$mp4->play('忍者', 'mp3');
// 播放一个wma
$mp4->play('彩虹', 'wma');
// 播放一个mp4
$mp4->play('龙卷风mv', 'mp4');
} catch (\Exception $e) {
echo $e->getMessage();
}