lundi 25 janvier 2021

Design pattern - Decorator

I try to learn design patterns. At this moment I got decorator. Product interface <?php declare(strict_types=1);

interface Product
{
    public function getPrice();

    public function getDescription();
}

BaseProduct

<?php declare(strict_types=1);

class BaseProduct implements Product
{
    public function getPrice()
    {
        return 20;
    }

    public function getDescription()
    {
        return "This is base product";
    }
}

SportProductDecorator

<?php declare(strict_types=1);

class SportProductDecorator implements Product
{
    private Product $product;

    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    public function getPrice()
    {
        return $this->product->getPrice() + 20;
    }

    public function getDescription()
    {
        return "THis is product from Sport category";
    }
}

HomeProductDecorator

<?php declare(strict_types=1);

class HomeProductDecorator implements Product
{
    private Product $product;

    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    public function getPrice()
    {
        return $this->product->getPrice() + 50;
    }

    public function getDescription()
    {
        return "This is product from Home category";
    }
}

Did I apply the decorator well here? Design patterns are taught, but it's tough. I have seen a lot of people do it in different ways.

Aucun commentaire:

Enregistrer un commentaire