简介

代理与装璜器很像,都是在原有类根底上,增量做改变。

不同在于,代理模式下,client 间接操作的就是 proxy 对象,new 的就是 proxy 对象,不能够让client 间接操作被代理对象,相当于原始类被齐全暗藏掉了。

类比现实生活,租房代理是不会让客户间接跟房东分割的,客户签合同也是跟代理签,全程没有跟房东交互。

角色

  • 根底性能接口 Subject

    定义根本动作

  • 被代理类

    实现 Subject 接口,实现业务逻辑

  • Proxy 代理类

    实现 Subject接口

类图

图中ServiceInterface是根底接口,定义一个operation办法。Service是被代理类,实现了ServiceInterface接口,Proxy是代理类,也实现了ServiceInterface接口。

Proxy类的operation办法做了CheckAccess操作,容许的话再调用被代理类的operation办法。

代码

interface Subject{    public function request(): void;}class RealSubject implements Subject{    public function request(): void    {        echo "RealSubject: Handling request.\n";    }}class Proxy implements Subject{    private $realSubject;    public function __construct(RealSubject $realSubject)    {        $this->realSubject = $realSubject;    }    public function request(): void    {        if ($this->checkAccess()) {            $this->realSubject->request();            $this->logAccess();        }    }    private function checkAccess(): bool    {        echo "Proxy: Checking access prior to firing a real request.\n";        return true;    }    private function logAccess(): void    {        echo "Proxy: Logging the time of request.\n";    }}function clientCode(Subject $subject){    $subject->request();}echo "Client: Executing the client code with a real subject:\n";$realSubject = new RealSubject();clientCode($realSubject);echo "\n";echo "Client: Executing the same client code with a proxy:\n";$proxy = new Proxy($realSubject);clientCode($proxy);

output:

Client: Executing the client code with a real subject:RealSubject: Handling request.Client: Executing the same client code with a proxy:Proxy: Checking access prior to firing a real request.RealSubject: Handling request.Proxy: Logging the time of request.

本文由mdnice多平台公布