-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDecorator.php
85 lines (69 loc) · 1.8 KB
/
Decorator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace DesignPatterns\Structural;
/**
* Decorator pattern lets you dynamically change the behavior of an object at run time
* by wrapping them in an object of a decorator class
*/
interface Coffee
{
public function getCost();
public function getDescription();
}
class SimpleCoffee implements Coffee
{
public function getCost()
{
return 10;
}
public function getDescription()
{
return 'Coffee';
}
}
class MilkCoffee implements Coffee
{
protected $coffee;
// injection
public function __construct(Coffee $coffee)
{
$this->coffee = $coffee;
}
// change, "decorate" the default behavior
public function getCost()
{
return $this->coffee->getCost() + 2;
}
public function getDescription()
{
return $this->coffee->getDescription() . ', with milk';
}
}
class VanillaCoffee implements Coffee
{
protected $coffee;
public function __construct(Coffee $coffee)
{
$this->coffee = $coffee;
}
public function getCost()
{
return $this->coffee->getCost() + 3;
}
public function getDescription()
{
return $this->coffee->getDescription() . ', with vanilla';
}
}
# Client code example
$coffee = new SimpleCoffee();
echo $coffee->getDescription() . ' - ' . $coffee->getCost() . PHP_EOL;
// apply the Decorator for the $coffee object
$milkCoffee = new MilkCoffee($coffee);
echo $milkCoffee->getDescription() . ' - ' . $milkCoffee->getCost() . PHP_EOL;
// we also can use chain calls of Decorators
$vanillaMilkCoffee = new VanillaCoffee(new MilkCoffee(new SimpleCoffee()));
echo $vanillaMilkCoffee->getDescription() . ' - ' . $vanillaMilkCoffee->getCost() . PHP_EOL;
/** Output:
Coffee - 10
Coffee, with milk - 12
Coffee, with milk, with vanilla - 15 */