-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy path19-interpreter.php
66 lines (54 loc) · 1.23 KB
/
19-interpreter.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
<?php
interface Converter
{
public function show();
}
// === A Simple Converter ===
// That convert Gallon to Litre
class GallonToLitre implements Converter
{
private $gallon;
public function __construct($gallon)
{
$this->gallon = $gallon;
}
public function show()
{
return round($this->gallon * 3.79);
}
}
// === A Simple Converter ===
// That convert Mile to Kilometer
class MileToKilometer implements Converter
{
private $mile;
public function __construct($mile)
{
$this->mile = $mile;
}
public function show()
{
return round($this->mile * 1.6);
}
}
// === An Intepreter ===
// That interpret to Kilometer per Litre by using existing converters.
// Consider this as structuring a sentence using grammers (converters).
class MpgToKml implements Converter
{
private $g2l;
private $m2k;
public function __construct(Converter $g2l, Converter $m2k)
{
$this->g2l = $g2l;
$this->m2k = $m2k;
}
public function show()
{
echo $this->g2l->show() . "l/" . $this->m2k->show() . "k\n";
}
}
// ---
$mpg2kml = new MpgToKml(new GallonToLitre(1), new MileToKilometer(20));
$mpg2kml->show();
// Output: 4l/32k