forked from eimg/design-patterns-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13-strategy.php
57 lines (47 loc) · 1005 Bytes
/
13-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
<?php
interface Car
{
public function pick();
}
class Fit implements Car
{
public function pick()
{
echo "Picking Fit for today.\n";
}
}
class Vitz implements Car
{
public function pick()
{
echo "Picking Vitz for today.\n";
}
}
// === CarPickerStrategy ===
// That decide which car object to use based on the situation
// The benefit is that we can add more strategies later,
// clients doesn't have to know or change their implementation
class CarPickerStrategy
{
public $today;
public function __construct($today)
{
$this->today = $today;
}
public function pick()
{
if( $this->today == "Monday" ) {
$car = new Vitz();
} else {
$car = new Fit();
}
$car->pick();
}
}
// ---
$carpicker = new CarPickerStrategy("Sunday");
$carpicker->pick();
// Output: Picking Fit for today.
$carpicker->today = "Monday";
$carpicker->pick();
// Output: Picking Vitz for today.