DEV Community

菜皮日记
菜皮日记

Posted on

结构型设计模式-代理 Proxy

简介

代理与装饰器很像,都是在原有类基础上,增量做改动。

不同在于,代理模式下,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);
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)