关于后端:结构型设计模式代理-Proxy

53次阅读

共计 1468 个字符,预计需要花费 4 分钟才能阅读完成。

简介

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

不同在于,代理模式下,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 多平台公布

正文完
 0