简介
代理与装饰器很像,都是在原有类基础上,增量做改动。
不同在于,代理模式下,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.
复制代码
评论