-
Notifications
You must be signed in to change notification settings - Fork 2
/
Composite.php
117 lines (93 loc) · 2.32 KB
/
Composite.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace DesignPatterns\Structural;
abstract class CartItem
{
protected $parent;
public function setParent(CartItem $parent)
{
$this->parent = $parent;
}
public function getParent(): CartItem
{
return $this->parent;
}
public function add(CartItem $cartItem)
{
}
public function remove(CartItem $cartItem)
{
}
public function isComposite(): bool
{
return false;
}
abstract public function getPrice(): float;
}
class Product extends CartItem
{
protected $name;
protected $price;
public function __construct(string $name, float $price)
{
$this->name = $name;
$this->price = $price;
}
public function getPrice(): float
{
return $this->price;
}
}
class CompositeProduct extends CartItem
{
protected $name;
/** @var CartItem[] */
protected $children = [];
public function __construct(string $name)
{
$this->name = $name;
}
public function add(CartItem $cartItem)
{
if (in_array($cartItem, $this->children, true)) {
return;
}
$this->children[] = $cartItem;
$cartItem->setParent($this);
}
public function remove(CartItem $cartItem)
{
$this->children = array_filter($this->children, function ($child) use ($cartItem) {
return $child == $cartItem;
});
$cartItem->setParent(null);
}
public function getPrice(): float
{
$totalPrice = 0;
foreach ($this->children as $child) {
$totalPrice += $child->getPrice();
}
return $totalPrice;
}
public function isComposite(): bool
{
return true;
}
}
# Client code example
$shoppingCart[] = new Product('Bike', 200);
$motorcycle = new CompositeProduct('Motorcycle');
$motorcycle->add(new Product('Motor', 700));
$motorcycle->add(new Product('Wheels', 300));
$frame = new CompositeProduct('Frame');
$frame->add(new Product('Steering', 200.00));
$frame->add(new Product('Seat', 100));
$motorcycle->add($frame);
$shoppingCart[] = $motorcycle;
// calculate a total price of shopping cart
$totalPrice = 0;
foreach ($shoppingCart as $cartItem) {
/** @var CartItem $cartItem */
$totalPrice += $cartItem->getPrice();
}
echo $totalPrice; // Output: 1500