设计模式 享元模式

WechatIMG35.jpeg

介绍

享元模式是一种结构型设计模式,它通过共享相同或相似的对象来减少内存的使用量,从而提高系统的性能和效率。

角色

角色 说明
Flyweight 享元对象
ConcreteFlyweight 内部状态的具体享元对象
UnsharedConcreteFlyweight 外部状态的具体享元对象
FlyweightFactory 享元工厂

角色示例

类名 担任角色 说明
Song 享元对象 歌曲
FreeSong 内部状态的具体享元对象 免费歌曲
VipSong 外部状态的具体享元对象 Vip 歌曲
QQMusic 享元工厂 QQMusic 播放器

UML类图

享元模式.jpg

代码

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
<?php
interface Song{
public function play();
public function download();
}

class FreeSong implements Song
{
public $name;
function __construct($name=null)
{
$this->name = $name;
}

public function play()
{
return '播放《'.$this->name.'》'.PHP_EOL;
}

public function download()
{
return '下载《'.$this->name.'》'.PHP_EOL;
}
}

class VipSong implements Song
{
public $name;
function __construct($name=null)
{
$this->name = $name;
}

public function play()
{
return '不是VIP,不能播放《'.$this->name.'》'.PHP_EOL;
}

public function download()
{
return '不是VIP,不能下载《'.$this->name.'》'.PHP_EOL;
}
}

class QQMusic
{
public $song;
protected static $myPlaylist;
function __construct($song)
{
$this->song = $song;
if (!isset(self::$myPlaylist)) {
self::$myPlaylist = [];
}
}

public function addMyPlaylist($name)
{
if (!array_key_exists($name,self::$myPlaylist)) {
self::$myPlaylist[$name] = $this->song->name = $name;
return '《'.$name.'》已添加到我的歌单'.PHP_EOL;
} else {
return '《'.$name.'》已存在于我的歌单'.PHP_EOL;
}
}
}

$freeSong = new FreeSong();
$qqMusic = new QQMusic($freeSong);
echo $qqMusic->addMyPlaylist('Faded');
echo $qqMusic->song->download();
echo $qqMusic->song->play();

echo $qqMusic->addMyPlaylist('Different World');
echo $qqMusic->song->download();
echo $qqMusic->song->play();

echo $qqMusic->addMyPlaylist('Faded');
echo $qqMusic->song->download();
echo $qqMusic->song->play();

$vipSong = new VipSong();
$qqMusic = new QQMusic($vipSong);
echo $qqMusic->addMyPlaylist('Lost Control');
echo $qqMusic->song->download();
echo $qqMusic->song->play();

echo $qqMusic->addMyPlaylist('Lily');
echo $qqMusic->song->download();
echo $qqMusic->song->play();

echo $qqMusic->addMyPlaylist('Lily');
echo $qqMusic->song->download();
echo $qqMusic->song->play();

创建 Test.php,内容如上。

执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ php Test.php
《Faded》已添加到我的歌单
下载《Faded》
播放《Faded》
《Different World》已添加到我的歌单
下载《Different World》
播放《Different World》
《Faded》已存在于我的歌单
下载《Different World》
播放《Different World》
《Lost Control》已添加到我的歌单
不是VIP,不能下载《Lost Control》
不是VIP,不能播放《Lost Control》
《Lily》已添加到我的歌单
不是VIP,不能下载《Lily》
不是VIP,不能播放《Lily》
《Lily》已存在于我的歌单
不是VIP,不能下载《Lily》
不是VIP,不能播放《Lily》
-------------本文结束感谢您的阅读-------------
0%