设计模式之代理模式--PHP

代理模式是常用的设计模式之一,代理模式为对象的间接访问提供了一套方案,可以对对象访问进行控制,也能监控对象访问相关的数据信息。

代理模式(Proxy)就是给某一个对象提供代理,在由代理控制原对象的访问。

代理模式的UML图:

设计模式之代理模式--PHP

 

下面是代理模式的demo:

1 <?php 2 /** 3 * @desc 代理模式 4 * Created by PhpStorm. 5 * User: zzq 6 * Date: 2019-02-13 7 * Time: 15:01 8 */ 9 10 //定义RealSubject 和 Proxy 共同具备的东西 11 interface Subject{ 12 function say(); 13 function run(); 14 } 15 //代理类 16 class Proxy implements Subject{ 17 private $realSubject = null; 18 public function __construct(RealObject $realObject = null){ 19 if ( empty($realObject) ) { 20 $this->realSubject = new RealObject(); 21 } else { 22 $this->realSubject = $realObject; 23 } 24 } 25 26 function say(){ 27 $this->realSubject->say(); 28 } 29 30 function run(){ 31 $this->realSubject->run(); 32 } 33 } 34 //真正的实体对象方法 35 class RealObject implements Subject{ 36 private $name; 37 public function __construct($name){ 38 $this->name = $name; 39 } 40 41 function say(){ 42 echo $this->name."说:我饿了"; 43 echo PHP_EOL; 44 } 45 46 function run(){ 47 echo $this->name."吃饱了,去跑步"; 48 echo PHP_EOL; 49 } 50 } 51 52 $subject = new RealObject("李四"); 53 $proxy = new Proxy($subject); 54 $proxy->say(); 55 $proxy->run();

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgfdf.html