• PHP设计模式系列


    • 委托模式

    通过分配或委托其他对象,委托设计模式能够去除核心对象中的判决和复杂的功能性。

    • 应用场景
    1. 设计了一个cd类,类中有mp3播放模式,和mp4播放模式
    2. 改进前,使用cd类的播放模式,需要在实例化的类中去判断选择什么方式的播放模式
    3. 改进后,播放模式当做一个参数传入playList函数中,就自动能找到对应需要播放的方法。
    • 代码:cd类,未改进之前,选择播放模式是一种痛苦的事情

    1. <?php  
    2. //委托模式-去除核心对象中的判决和复杂的功能性  
    3. //使用委托模式之前,调用cd类,选择cd播放模式是复杂的选择过程  
    4. class cd {  
    5.     protected $cdInfo = array();   
    6.       
    7.     public function addSong($song) {  
    8.         $this->cdInfo[$song] = $song;  
    9.     }  
    10.       
    11.     public function playMp3($song) {  
    12.         return $this->cdInfo[$song] . '.mp3';  
    13.     }  
    14.       
    15.     public function playMp4($song) {  
    16.         return $this->cdInfo[$song] . '.mp4';  
    17.     }  
    18. }  
    19. $oldCd = new cd;  
    20. $oldCd->addSong("1");  
    21. $oldCd->addSong("2");  
    22. $oldCd->addSong("3");  
    23. $type = 'mp3';  
    24. if ($type == 'mp3') {  
    25.     $oldCd->playMp3();  
    26. else {  
    27.     $oldCd->playMp4();  
    28. }  

    • 代码:通过委托模式,改进后的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'); //只要传递参数就能知道需要选择何种播放模式  


    参考:《PHP设计模式》Aaron Saray著
  • 相关阅读:
    js动态生成表格
    Android Studio使用小技巧:提取方法代码片段
    Android适配底部虚拟按键的方法
    Eclipse注释模板
    android7.0关于TelephonyManager.getDeviceId()返回null的问题
    在fragment中实现返回键单击提醒 双击退出
    android使用友盟实现第三方登录、分享以及微信回调无反应问题解决办法
    【FastDev4Android框架开发】RecyclerView完全解析之下拉刷新与上拉加载SwipeRefreshLayout(三十一)
    WebView使用详解(二)——WebViewClient与常用事件监听
    android正则表达式隐藏邮箱地址中间字符
  • 原文地址:https://www.cnblogs.com/wanghaitao/p/9440351.html
Copyright © 2020-2023  润新知