国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

什么是代理模式?(實例說明)

2024-05-04 21:50:59
字體:
來源:轉載
供稿:網友

代理模式:代理模式的作用和繼承以及接口和組合的作用類似,都是為了聚合共用部分,減少公共部分的代碼。

不同的是相比起繼承,他們的語境不同,繼承要表達的含義是 is-a, 而代理要表達的含義更接近于接口, 是 has-a,而且使用代理的話應了一句話"少用繼承,多用組合",要表達的意思其實也就是降低耦合度了。

對于組合來說,他比組合更具靈活性,比如我們將代理對象設為private,那么我可以選擇只提供一部分的代理功能,例如Printer的某一個或兩個方法,又或者在提供Printer的功能的時候加入一些其他的操作,這些都是可以的。

  1. <?php 
  2.  
  3. //代理對象,一臺打印機 
  4.  
  5. class Printer {  
  6.  
  7.     public function printSth() { 
  8.  
  9.         echo '我可以打印<br>'
  10.  
  11.     } 
  12.  
  13.  
  14. //這是一個文印處理店,只文印,賣紙,不照相 
  15.  
  16. class TextShop { 
  17.  
  18.     private $printer
  19.  
  20.     public function __construct(Printer $printer) { 
  21.  
  22.         $this->printer = $printer
  23.  
  24.     } 
  25.  
  26.     //賣紙 
  27.  
  28.     public function sellPaper() { 
  29.  
  30.         echo 'give you some paper <br>'
  31.  
  32.     } 
  33.  
  34.     //將代理對象有的功能交給代理對象處理 
  35.  
  36.     public function __call($method$args) { 
  37.  
  38.         if(method_exists($this->printer, $method)) { 
  39.  
  40.             $this->printer->$method($args); 
  41.  
  42.         } 
  43.  
  44.     } 
  45.  
  46.  
  47. //這是一個照相店,只文印,拍照,不賣紙 
  48.  
  49. class PhotoShop {     
  50.  
  51.     private $printer
  52.  
  53.       
  54.  
  55.     public function __construct(Printer $printer) { 
  56.  
  57.         $this->printer = $printer
  58.  
  59.     } 
  60.  
  61.       
  62.  
  63.     public function takePhotos() {    //照相 
  64.  
  65.         echo 'take photos for you <br>'
  66.  
  67.     } 
  68.  
  69.       
  70.  
  71.     public function __call($method$args) {    //將代理對象有的功能交給代理對象處理 
  72.  
  73.         if(method_exists($this->printer, $method)) { 
  74.  
  75.             $this->printer->$method($args); 
  76.  
  77.         } 
  78.  
  79.     } 
  80.  
  81.  
  82. $printer = new Printer(); 
  83.  
  84. $textShop = new TextShop($printer); 
  85.  
  86. $photoShop = new PhotoShop($printer); 
  87.  
  88. $textShop->printSth(); 
  89.  
  90. $photoShop->printSth(); 

上一篇:外觀模式的作用

下一篇:裝飾模式詳解

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邳州市| 大宁县| 黑水县| 章丘市| 汝阳县| 中江县| 景洪市| 丁青县| 大港区| 鹰潭市| 芜湖县| 隆回县| 百色市| 察哈| 农安县| 临夏市| 长春市| 土默特左旗| 牡丹江市| 东平县| 上虞市| 延庆县| 桐城市| 阳东县| 河东区| 定陶县| 重庆市| 五家渠市| 东丽区| 介休市| 贵溪市| 浦江县| 临江市| 平度市| 卢湾区| 聂拉木县| 潮州市| 黄龙县| 贵阳市| 苏尼特左旗| 咸阳市|