Proper use of decorator

I have a Products class. Now I want to add some kind of discount module to my website that should interact with the Products class.

Currently, the only solution I can come up with is to use some kind of decorator pattern to wrap around the product class so that it can change the price of the product.

Like this:

class Product {
    function price() {
        return 10;
    }
}

class ProductDiscountDecorator {
    private $product;

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

    function price() {
        return $this->product->price()*0.8;
    }
}

$product = new ProductDiscountDecorator(new Product());
echo $product->price();

This is a discount, prices must be adjusted on each page of the website. Therefore, each page using the Product class must also add a decorator. The only way to solve this problem is to use a factory that automatically adds this decorator.

$product = $factory->get('product'); // returns new ProductDiscountDecorator(new Product());

Maybe this will work, but I feel like I'm using the decorator pattern incorrectly here.

, , - ? - ?

+5
2

- .

class Product
{
    protected $discountStrategy;
    protected $price;

    public function __construct(DiscountStrategy $discountStrategy)
    {
        $this->discountStrategy = $discountStrategy;
    }

    public function getPrice()
    {
        return $this->discountStrategy->applyDiscount($this->price);
    }
}

:

interface DiscountStrategy 
{
    public function applyDiscount($cent);
}

class NoDiscount implements DiscountStrategy
{
    public function applyDiscount($cent)
    {
        return $cent;
    }
}

class PremiumDiscount implements DiscountStrategy
{
    public function applyDiscount($cent)
    {
        return $cent - $cent * 0.8;
    }
}

Factory , , , , , .

+2

.

, ""

.

interface IProduct { public function getPrice(); }

Product, ProductDiscountDecorator

class Product implements IProduct { ... }
class ProductDiscountDecorator implements IProduct { ... }
0

All Articles