-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDrinkFactory.php
52 lines (43 loc) · 1.35 KB
/
DrinkFactory.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
declare(strict_types=1);
class DrinkFactory
{
private $drinkCache;
public $drinksCreated = 0;
public function __construct()
{
$this->drinkCache = [];
}
public function getDrink(string $drinkKey)
{
$drink = null;
if (array_key_exists($drinkKey, $this->drinkCache)) {
echo "Reusing existing flyweight object for " . $drinkKey . "\n\n";
return $this->drinkCache[$drinkKey];
} else {
echo "Creating new flyweight object for " . $drinkKey . "\n\n";
switch($drinkKey)
{
case "Espresso":
$drink = new Espresso();
break;
case "Banana Smoothie":
$drink = new BananaSmoothie();
break;
case "Cappuccino":
$drink = new Cappuccino();
break;
default:
throw new Exception("This is not a flyweight drink object");
}
}
$this->drinkCache[$drinkKey] = $drink;
$this->drinksCreated++;
return $drink;
}
public function listDrinks()
{
echo "Factory has " . count($this->drinkCache) . " drink objects ready to use\n\n";
echo "Number of objects created: " . $this->drinksCreated . "\n\n";
}
}