Created
September 21, 2016 13:21
-
-
Save arekrob/69783302dcfb326cce2165e60ea6c3cb to your computer and use it in GitHub Desktop.
Decorator pattern - a good example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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