
<?php
//Subject
abstract class Graphic {
protected $fileName = "";
abstract function draw();
function getFileName(): string {
return $this->fileName;
}
}
//RealSubject
class Image extends Graphic {
function __construct(string $fileName) {
$this->fileName = $fileName;
}
//Request()
function draw() {
echo "draw " . $this->fileName, "\n";
}
}
//Proxy
class ImageProxy extends Graphic {
private $image = null;
function __construct(string $fileName) {
$this->fileName = $fileName;
}
function draw() {
$this->getImage()->draw();
}
function getImage(): Image {
if ($this->image == null) {
$this->image = new Image($this->fileName);
}
return $this->image;
}
}
//Client
$proxy = new ImageProxy("1.png");
//operation without creating a RealSubject
$fileName = $proxy->getFileName();
//forwarded to the RealSubject
$proxy->draw();
| Подменяет другой объект для контроля доступа к нему. Заместитель реализует интерфейс первоначального объекта. |