- 委托模式
通过分配或委托其他对象,委托设计模式能够去除核心对象中的判决和复杂的功能性。
- 应用场景
- 设计了一个cd类,类中有mp3播放模式,和mp4播放模式
- 改进前,使用cd类的播放模式,需要在实例化的类中去判断选择什么方式的播放模式
- 改进后,播放模式当做一个参数传入playList函数中,就自动能找到对应需要播放的方法。
- 代码:cd类,未改进之前,选择播放模式是一种痛苦的事情
1. //委托模式-去除核心对象中的判决和复杂的功能性
2. //使用委托模式之前,调用cd类,选择cd播放模式是复杂的选择过程
3. class cd {
4. protected $cdInfo = array();
5.
6. public function addSong($song) {
7. $this->cdInfo[$song] = $song;
8. }
9.
10. public function playMp3($song) {
11. return $this->cdInfo[$song] . '.mp3';
12. }
13.
14. public function playMp4($song) {
15. return $this->cdInfo[$song] . '.mp4';
16. }
17. }
18. $oldCd = new cd;
19. $oldCd->addSong("1");
20. $oldCd->addSong("2");
21. $oldCd->addSong("3");
22. $type = 'mp3';
23. if ($type == 'mp3') {
24. $oldCd->playMp3();
25. } else {
26. $oldCd->playMp4();
27. }
- 代码:通过委托模式,改进后的cd类
1. <?php
2. //委托模式-去除核心对象中的判决和复杂的功能性
3. //改进cd类
4. class cdDelegate {
5. protected $cdInfo = array();
6.
7. public function addSong($song) {
8. $this->cdInfo[$song] = $song;
9. }
10.
11. public function play($type, $song) {
12. $obj = new $type;
13. return $obj->playList($this->cdInfo, $song);
14. }
15. }
16.
17. class mp3 {
18. public function playList($list) {
19. return $list[$song];
20. }
21. }
22.
23. class mp4 {
24. public function playList($list) {
25. return $list[$song];
26. }
27. }
28.
29. $newCd = new cd;
30. $newCd->addSong("1");
31. $newCd->addSong("2");
32. $newCd->addSong("3");
33. $type = 'mp3';
34. $oldCd->play('mp3', '1'); //只要传递参数就能知道需要选择何种播放模式