* @var RealImage */ private $realImage; private $fileName; /** * @param $fileName */ public function __construct($fileName) { $this->fileName = $fileName; } public function displayImage() { if ($this->realImage === null) { $this->realImage = new RealImage($this->fileName); } $this->realImage->displayImage(); } } $image1 = new ProxyImage("my_awsome_photo_1.jpg"); $image2 = new ProxyImage("my_awsome_photo_2.jpg"); $image1->displayImage(); // loading necessary $image1->displayImage(); // loading unnecessary $image2->displayImage(); // loading necessary $image2->displayImage(); // loading unnecessary $image1->displayImage(); // loading unnecessary
{ echo "Display {$this->filename}\n"; } } class ProxyImage implements ImageInterface { protected $image; public function __construct($filename) { $this->filename = $filename; } public function display() { if (null === $this->image) { $this->image = new Image($this->filename); } return $this->image->display(); } } // Usage example $filename = 'test.png'; $image1 = new Image($filename); // loading necessary echo $image1->display(); // loading unnecessary $image2 = new ProxyImage($filename); // loading unnecessary echo $image2->display(); // loading necessary echo $image2->display(); // loading unnecessary
<?php require 'ImageInterface.php'; require 'ProxyImage.php'; require 'RealImage.php'; $image1 = new ProxyImage("blow-your-mind.gif"); $image2 = new ProxyImage("thumbs-up.gif"); $image1->showImage(); $image1->showImage(); $image1->showImage(); $image2->showImage(); $image2->showImage();
<?php require 'Image.php'; require 'ProxyImage.php'; // Result in three times loading the image $image = new Image('foo.jpg'); $image->getImageContents(); // Loads the image $image->getImageContents(); // Loads the image $image->getImageContents(); // Loads the image // Result in only loading once $image = new ProxyImage('foo.jpg'); $image->getImageContents(); // Loads the image $image->getImageContents(); // Does not load the image $image->getImageContents(); // Does not load the image