/ Gists / 16. Template Method
On gists

16. Template Method

Navrhove vzory - Bohmer

template-method.php Raw #

<?php

/*

Návrhový vzor Template Method definuje rozhraní algoritmu v metodě a přenechává
implementaci jednotlivých kroků potomkům třídy. Ti mohou jednotlivé části
algoritmu modifikovat, aniž by změnili jeho strukturu.

*/


abstract class AbstractPrinter implements Printer, Observable
{
    // ... atributy a metody původní třídy LaserPrinter
    protected $paperAmount = 150;
    
    abstract protected function replaceCartridges();
    abstract protected function checkPrintingParts();
    abstract protected function isLowPaperAmount();

    protected function addPaper()
    {
        printf(
            "Doplnění %d listů do zásobníku papíru.\n",
            1000 - $this->paperAmount
        );
        $this->paperAmount = 1000;
    }
    final public function check()
    {
        printf("Probíhá kontola tiskárny %s:\n", $this->type);
        $this->replaceCartridges();
        $this->checkPrintingParts();
        if ($this->isLowPaperAmount()) {
            $this->addPaper();
        } else {
            print "Dostatečné množství papíru.\n";
        }
    }
}


class LaserPrinter extends AbstractPrinter
{
    protected function replaceCartridges()
    {
        print "Výměna toneru typu AAA-111.\n";
    }

    protected function checkPrintingParts()
    {
        print "Kontrola fotoválce.\n";
    }

    protected function isLowPaperAmount()
    {
        if ($this->paperAmount < 200) {
            return true;
        }
        return false;
    }
}


class InkjetPrinter extends AbstractPrinter
{
    protected function replaceCartridges()
    {
        print "Výměna inkoustových náplní typu BBB-222.\n";
    }

    protected function checkPrintingParts()
    {
        print "Kontrola trysek.\n";
    }

    protected function isLowPaperAmount()
    {
        if ($this->paperAmount < 100) {
            return true;
        }
        return false;
    }
}


$laserPrinter = new LaserPrinter('LP-1');
$inkjetPrinter = new InkjetPrinter('IP-1');

$laserPrinter->check();
$inkjetPrinter->check();