1 <?php
2
3 /**
4 * 和装饰器模式的区别:装饰器模式为了增强功能,而代理模式是为了加以控制
5 *
6 * 装饰器为对象添加一个或多个功能,而代理则控制对对象的访问
7 */
8
9 interface image
10 {
11 public function display();
12 }
13
14 class RealImage implements image
15 {
16 private $_imgSrc;
17
18 public function __construct($imgSrc)
19 {
20 $this->_imgSrc = $imgSrc;
21 $this->loadFromDisk();
22 }
23
24 private function loadFromDisk()
25 {
26 echo "Load {$this->_imgSrc} from disk<br/>";
27 }
28
29 public function display()
30 {
31 echo "Display {$this->_imgSrc}";
32 }
33 }
34
35
36 class ProxyImage implements image
37 {
38 private $_imgSrc;
39 private $_realImage;
40
41 public function __construct($imgSrc)
42 {
43 $this->_imgSrc = $imgSrc;
44 }
45
46 public function display()
47 {
48 if (!$this->_realImage instanceof RealImage) {
49 $this->_realImage = new RealImage($this->_imgSrc);
50 }
51
52 $this->_realImage->display();
53 }
54 }
55
56
57
58 $p = new ProxyImage('a.png');
59 $p->display();
60
61 echo "<br/><br/>";
62 $p->display();