-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactory.php
More file actions
69 lines (55 loc) · 1.36 KB
/
Copy pathFactory.php
File metadata and controls
69 lines (55 loc) · 1.36 KB
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
<?php
declare(strict_types = 1);
namespace Factory;
interface FoodInterface
{
public function getCalories(): float;
}
class Apple implements FoodInterface
{
public function getCalories(): float
{
$calories = 52 / 100;
return $calories;
}
}
class Orange implements FoodInterface
{
public function getCalories(): float
{
$calories = 47 / 100;
return $calories;
}
}
class FoodFactory
{
public function create(string $type)
{
$instance = null;
if ($type === 'orange') {
$instance = new Orange();
} else if ($type === 'apple') {
$instance = new Apple();
}
return $instance;
}
}
class CaloriesCalculator
{
public function calculateCalories($weight, $type): float
{
$productFactory = new FoodFactory();
$product = $productFactory->create($type);
if (!$product instanceof FoodInterface) {
throw new \Exception('Unknown product type');
}
$calories = $product->getCalories();
$total = $calories * $weight;
return $total;
}
}
$calories_calculator = new CaloriesCalculator();
$p_type = 'apple';
$p_weight = 100;
$total_calories = $calories_calculator->calculateCalories($p_weight, $p_type);
echo sprintf('%dg. of %s has %.0F calories', $p_weight, $p_type, $total_calories);