Skip to content

Instantly share code, notes, and snippets.

@arekrob
Created September 21, 2016 13:21
Show Gist options
  • Save arekrob/69783302dcfb326cce2165e60ea6c3cb to your computer and use it in GitHub Desktop.
Save arekrob/69783302dcfb326cce2165e60ea6c3cb to your computer and use it in GitHub Desktop.
Decorator pattern - a good example
interface IProduct {
getName();
getPrice();
}
class Product implements IProduct {
private $name;
private $price;
getName() {...}
getPrice() {...}
}
/**
* A product that is added to customer's basket for free (a gift).
*/
class GiftProduct implements IProduct {
private $product;
__construct(IProduct $product) {
$this->product = $product;
}
getName() {
return $this->product->getName() . " (gift)";
}
getPrice() {
return 0; //gifts are for free
}
}
/**
* More than one product sold as one set (bundle), eg. a laptop + mouse.
*/
class SetOfProducts implements IProduct {
private $name;
private $products = [];
__construct($name) {
$this->name = $name;
}
addComponent(IProduct $product) {
$this->products[] = $product;
}
getName() {
return $this->name;
}
getPrice() {
//return sum of prices of all the products
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment