Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Decorator Pattern
<?php
$macbook = new Macbook();
echo 'Una Macbook con pantalla de 13 pulgadas cuesta ' . $macbook->getPrice() . ' euros' . PHP_EOL;
$macbook15Pulg = new WithDisplaySize15(new Macbook());
echo 'Una Macbook con pantalla de 15 pulgadas cuesta ' . $macbook15Pulg->getPrice() . ' euros' . PHP_EOL;
$macbook17Pulg = new WithDisplaySize17(new Macbook());
echo 'Una Macbook con pantalla de 17 pulgadas cuesta ' . $macbook17Pulg->getPrice() . ' euros' . PHP_EOL;
$macbookPro = new MacbookPro(new Macbook());
echo 'Una Macbook Pro con pantalla de 13 pulgadas cuesta ' . $macbookPro->getPrice() . ' euros' . PHP_EOL;
$macbookPro15Pulg = new WithDisplaySize15(new MacbookPro(new Macbook()));
echo 'Una Macbook Pro con pantalla de 15 pulgadas cuesta' . $macbookPro15Pulg->getPrice() . ' euros' . PHP_EOL;
$macbookPro17Pulg = new WithDisplaySize17(new MacbookPro(new Macbook()));
echo 'Una Macbook Pro con patanlla de 17 pulgadas cuesta ' . $macbookPro17Pulg->getPrice() . ' euros' . PHP_EOL;
<?php
class Macbook
{
protected $basePrice = 1500;
public function getPrice()
{
return $this->basePrice;
}
}
<?php
abstract class MacbookDecorator
{
protected $price;
protected $macbook;
public function __construct($macbook)
{
$this->macbook = $macbook;
}
public function getPrice()
{
return $this->macbook->getPrice() + $this->price;
}
}
<?php
class MacbookPro extends MacbookDecorator
{
protected $price = 950;
}
<?php
class WithDisplaySize15 extends MacbookDecorator
{
protected $price = 350;
}
<?php
class WithDisplaySize17 extends MacbookDecorator
{
protected $price = 700;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.