forked from Djuki/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStrategy.php
111 lines (97 loc) · 2.12 KB
/
Strategy.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
<?php
namespace DesignPatterns;
/**
* strategy pattern
*
* Terminology:
* - Context
* - Strategy
* - Concrete Strategy
*
* Purpose:
* to separate strategies and to enable fast switching between them.
* also this pattern is a good alternative to inheritance (instead of having an abstract class that is extended)
*
* Examples:
* - sorting a list of objects, one strategy by date, the other by id
* - simplify unit testing: e.g. switching between file and in-memory storage
*
*/
interface Comparator
{
/**
* @abstract
* @param object $a
* @param object $b
* @return bool
*/
public function compare($a, $b);
}
class ObjectCollection
{
private $_elements;
private $_comparator;
/**
* @param array $elements
*/
public function __construct(array $elements = array())
{
$this->_elements = $elements;
}
/**
* @return array
*/
public function sort()
{
$callback = array($this->_comparator, 'compare');
uasort($this->_elements, $callback);
return $this->_elements;
}
/**
* @param Comparator $comparator
* @return void
*/
public function setComparator(Comparator $comparator)
{
$this->_comparator = $comparator;
}
}
class IdComparator implements Comparator
{
public function compare($a, $b)
{
if ($a['id'] == $b['id']) {
return 0;
} else {
return $a['id'] < $b['id'] ? -1 : 1;
}
}
}
class DateComparator implements Comparator
{
public function compare($a, $b)
{
$aDate = strtotime($a['date']);
$bDate = strtotime($b['date']);
if ($aDate == $bDate) {
return 0;
} else {
return $aDate < $bDate ? -1 : 1;
}
}
}
$elements = array(
array(
'id' => 2,
'date' => '2011-01-01',
),
array(
'id' => 1,
'date' => '2011-02-01'
)
);
$collection = new ObjectCollection($elements);
$collection->setComparator(new IdComparator());
$collection->sort();
$collection->setComparator(new DateComparator());
$collection->sort();