-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy path2-abstract-factory.php
85 lines (68 loc) · 1.5 KB
/
2-abstract-factory.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
<?php
class CarOptions
{
var $color = "White";
var $doors = 4;
}
class Car
{
private $color;
private $doors;
public function __construct(CarOptions $options)
{
$this->color = $options->color;
$this->doors = $options->doors;
}
public function info()
{
return "This is a $this->doors doors $this->color car.\n";
}
}
// === Abstract/Guideline to creat CarFactory ===
// This help use create interchangable factories
// See also: Factory Method pattern
abstract class CarFactory
{
abstract public function build();
}
class RedCarFactory extends CarFactory
{
private $options;
public function __construct($doors)
{
$options = new CarOptions();
$options->color = "Red";
$options->doors = $doors;
$this->options = $options;
}
public function build()
{
return new Car($this->options);
}
}
class BlueCarFactory extends CarFactory
{
private $options;
public function __construct($doors)
{
$options = new CarOptions();
$options->color = "Blue";
$options->doors = $doors;
$this->options = $options;
}
public function build()
{
return new Car($this->options);
}
}
// ---
$color = "Blue";
// Deciding which factory to use
if($color == "Blue") {
$factory = new BlueCarFactory(5);
} elseif($color == "Red") {
$factory = new RedCarFactory(4);
}
$car = $factory->build();
echo $car->info();
// Output: This is a 5 doors Blue car.