当前位置:首页 > PHP教程 > php高级应用 > 列表

什么是代理模式?(实例说明)

发布:smiling 来源: PHP粉丝网  添加日期:2020-02-17 19:22:04 浏览: 评论:0 

代理模式:代理模式的作用和继承以及接口和组合的作用类似,都是为了聚合共用部分,减少公共部分的代码。

不同的是相比起继承,他们的语境不同,继承要表达的含义是 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.  
  17. class TextShop { 
  18.  
  19.     private $printer; 
  20.  
  21.     public function __construct(Printer $printer) { 
  22.  
  23.         $this->printer = $printer; 
  24.  
  25.     } 
  26.  
  27.     //卖纸 
  28.  
  29.     public function sellPaper() { 
  30.  
  31.         echo 'give you some paper <br>'; 
  32.  
  33.     } 
  34.  
  35.     //将代理对象有的功能交给代理对象处理 
  36.  
  37.     public function __call($method, $args) { 
  38.  
  39.         if(method_exists($this->printer, $method)) { 
  40.  
  41.             $this->printer->$method($args); 
  42.  
  43.         } 
  44.  
  45.     } 
  46.  
  47. } 
  48.  
  49. //这是一个照相店,只文印,拍照,不卖纸 
  50.  
  51. class PhotoShop {     
  52.  
  53.     private $printer; 
  54.  
  55.       
  56.  
  57.     public function __construct(Printer $printer) { 
  58.  
  59.         $this->printer = $printer; 
  60.  
  61.     } 
  62.  
  63.       
  64.  
  65.     public function takePhotos() {    //照相 
  66.  
  67.         echo 'take photos for you <br>'; 
  68.  
  69.     } 
  70.  
  71.       
  72.  
  73.     public function __call($method, $args) {    //将代理对象有的功能交给代理对象处理 
  74.  
  75.         if(method_exists($this->printer, $method)) { 
  76.  
  77.             $this->printer->$method($args); 
  78.  
  79.         } 
  80.  
  81.     } 
  82.  
  83. } 
  84.  
  85. $printer = new Printer(); 
  86.  
  87. $textShop = new TextShop($printer); 
  88.  
  89. $photoShop = new PhotoShop($printer); 
  90.  
  91. $textShop->printSth(); 
  92.  
  93. $photoShop->printSth(); 

Tags: 什么是代理模式

分享到: