ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 当你希望在无需修改客户代码的前提下于已有类的对象上增加额外行为时,该模式是无可替代的 ## 添加日志行为 <details> <summary>main.php</summary> ``` <?php namespace RefactoringGuru\Proxy\Conceptual; // 服务接口 interface Subject{ public function request(): void; } // 服务 class RealSubject implements Subject{ public function request(): void{ echo "RealSubject: Handling request.\n"; } } // 代理 class Proxy implements Subject{ /** * @var RealSubject */ 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{ // Some real checks should go here. 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(); // ... } $realSubject = new RealSubject(); $proxy = new Proxy($realSubject); clientCode($proxy); ``` </details> <br /> 输出 ``` Proxy: Checking access prior to firing a real request. RealSubject: Handling request. Proxy: Logging the time of request. ``` ### 缓存接口 **代理**类型有无数种:缓存、日志、访问控制和延迟初始化等 本例演示了代理模式如何通过对结果进行缓存来提高下载器对象的性能 <details> <summary>main.php</summary> ``` <?php namespace RefactoringGuru\Proxy\RealWorld; interface Downloader { public function download(string $url): string; } class SimpleDownloader implements Downloader { public function download(string $url): string { echo "Downloading a file from the Internet.\n"; $result = file_get_contents($url); echo "Downloaded bytes: " . strlen($result) . "\n"; return $result; } } class CachingDownloader implements Downloader { /** * @var SimpleDownloader */ private $downloader; /** * @var string[] */ private $cache = []; public function __construct(SimpleDownloader $downloader) { $this->downloader = $downloader; } public function download(string $url): string { if (!isset($this->cache[$url])) { echo "CacheProxy MISS. "; $result = $this->downloader->download($url); $this->cache[$url] = $result; } else { echo "CacheProxy HIT. Retrieving result from cache.\n"; } return $this->cache[$url]; } } function clientCode(Downloader $subject) { $result = $subject->download("http://example.com/"); // 重复下载请求可缓存的速度增加。 $result = $subject->download("http://example.com/"); } $realSubject = new SimpleDownloader(); $proxy = new CachingDownloader($realSubject); clientCode($proxy); ``` </details> <br /> 输出 ``` CacheProxy MISS. Downloading a file from the Internet. Downloaded bytes: 1256 CacheProxy HIT. Retrieving result from cache. ```