0%

设计模式之适配器模式

适配器是一个接口转换器,它可以是一个独立的硬件接口设备,允许硬件或电子接口与其它硬件或电子接口相连,也可以是信息接口。比如:电源适配器、三角架基座转接部件、USB与串口的转接设备等。

一、概念

  1. 适配器模式,作为两个不兼容的接口之间的桥梁,是指将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。

二、实现

  1. 定义类
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
interface MediaPlayer 
{
public function play($type, $name);
}

interface AdvancedMediaPlayer
{
public function playVlc($name);
public function playMp4($name);
}

class VlcPlayer implements AdvancedMediaPlayer
{
public function playVlc ($name)
{
echo "播放VLC文件: " . $name, PHP_EOL;
}

public function playMp4 ($name)
{
//none
}
}

class Mp4Player implements AdvancedMediaPlayer
{
public function playVlc ($name)
{
//none
}

public function playMp4 ($name)
{
echo "播放MP4文件: " . $name, PHP_EOL;
}
}

class MediaAdapter implements MediaPlayer
{
public $advanced;

public function __construct ($type)
{
if ($type == "vlc") {
$this->advanced = new VlcPlayer();
} else if ($type == "mp4") {
$this->advanced = new Mp4Player();
}
}

public function play ($type, $name)
{
if ($type == "vlc") {
$this->advanced->playVlc($name);
} else if ($type == "mp4") {
$this->advanced->playMp4($name);
}
}
}

class AudioPlayer implements MediaPlayer
{
public $adapter;

public function play ($type, $name)
{
if ($type == "mp3") {
echo "播放MP3文件: " . $name, PHP_EOL;
} else if (in_array($type, ["vlc", "mp4"])) {
$this->adapter = new MediaAdapter($type);
$this->adapter->play($type, $name);
} else {
echo "不支持".$type."格式", PHP_EOL;
}
}
}
  1. 调用
1
2
3
4
5
6
$audioPlayer = new AudioPlayer();

$audioPlayer->play("mp3", "1.mp3");
$audioPlayer->play("mp4", "2.mp4");
$audioPlayer->play("vlc", "3.vlc");
$audioPlayer->play("avi", "4.avi");