-
Notifications
You must be signed in to change notification settings - Fork 4
/
composite.php
53 lines (43 loc) · 1.06 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
<?php
/**
* Composite pattern example
*
* @author Christian Bergau <[email protected]>
* @copyright Free for all
* @link http://en.wikipedia.org/wiki/Composite_pattern
*/
interface ComponentInterface
{
public function operation();
}
class ConcreteComponent implements ComponentInterface
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function operation()
{
echo '['.$this->name.'] operation done';
}
}
class Composite implements ComponentInterface
{
protected $components = array();
public function add(ComponentInterface $component)
{
$this->components[] = $component;
}
public function operation()
{
foreach ($this->components as $component) {
$component->operation();
}
}
}
$composite = new Composite();
$composite->add(new ConcreteComponent('FirstComponent'));
$composite->add(new ConcreteComponent('SecondComponent'));
$composite->add(new ConcreteComponent('ThirdComponent'));
$composite->operation();