Skip to content

Instantly share code, notes, and snippets.

@weburnit
Last active October 9, 2015 09:37
Show Gist options
  • Save weburnit/11a521ffcd92139d1fa1 to your computer and use it in GitHub Desktop.
Save weburnit/11a521ffcd92139d1fa1 to your computer and use it in GitHub Desktop.
BackupHandler
<?php
interface BackupPowerDelegateInteface
public function successTurnonPowerBackup();
public function successTurnonPowerBackup();
}
<?php
class BackupPowerHandler
{
/**
* @var BackupPowerDelegateInteface
*/
protected $delegate;
public function setDelegate(BackupPowerDelegateInteface $delegate)
{
$this->delegate = $delegate;
}
public function turnOnPower()
{
$turnedOn = rand(0, 1);
if($turnedOn)
$this->delegate->successTurnonPowerBackup();
else $this->delegate->errorTurnonPowerBackup();
}
}
<?php
class OfficeDelegate implements PrintingDelegate, BackupPowerDelegateInterface
{
/**
* @var BackupPowerHandler
*/
private $backupHandler;
/**
* @var PrinterHandler
*/
private $printer;
/**
* OfficeDelegate constructor.
*
* @param $backupHandler
* @param $printer
*/
public function __construct(BackupPowerHandler $backupPowerHandler, PrinterHandler $printer)
{
$this->backupHandler = $backupPowerHandler;
$this->printer = $printer;
}
public function process()
{
$printingHandler = new PrinterHandler($this);
$printingHandler->printDocument();
if (!$this->turnOnPower()) {
$backupPowerHandler = new BackupPowerHandler();
$backupPowerHandler->setDelegate($this);
$backupPowerHandler->turnOnPower();
}
}
/**
* @return boolean
*/
private function turnOnPower()
{
return boolval(rand(0, 1));
}
/**
* Implement method to receive printing document from printer
*
* @param array $documents
*/
public function pickPrintingDocument(array $documents)
{
foreach ($documents as $doc) {
echo 'Received document: ' . $doc;
}
}
public function successTurnonPowerBackup()
{
echo 'Power is turned on successfully';
}
public function errorTurnonPowerBackup()
{
throw new Exception('Can not turn on backup power!');
}
}
<?php
class PrinterHandler
{
/**
* @var PrintingDelegate
*/
private $delegate;
public function __construct($delegate = null)
{
if ($delegate) {
$this->delegate = $delegate;
}
}
public function setDelegate(PrintingDelegate $delegate)
{
$this->delegate = $delegate;
}
private function chargeInk()
{
echo 'Charging ink';
}
public function printDocument()
{
$this->chargeInk();
$documents = [];
for ($i = 0; $i < 10; $i++) {
$documents[$i] = 'Document ' . $i;
}
$this->delegate->pickPrintingDocument($documents);
}
}
<?php
interface PrintingDelegateInterface
{
public function pickPrintingDocument(array $documents);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment