-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserverDesignPatternDemo.php
More file actions
78 lines (66 loc) · 2.13 KB
/
Copy pathobserverDesignPatternDemo.php
File metadata and controls
78 lines (66 loc) · 2.13 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
70
71
72
73
74
75
76
77
78
<?php
// Cette classe est observée par currentWeatherDisplay
class WeatherStation
{
private $observers = [];
private $temperature;
private $humidity;
private $pressure;
public function addObserver(currentWeatherDisplay $observer)
{
$this->observers[] = $observer;
}
public function removeObserver(currentWeatherDisplay $observer)
{
$key = array_search($observer, $this->observers, true);
if ($key !== false) {
unset($this->observers[$key]);
}
}
public function notifyObserver()
{
foreach ($this->observers as $observer) {
$observer->update($this->temperature, $this->humidity, $this->pressure);
}
}
public function setMeasurements(float $temperature, float $humidity, float $pressure)
{
$this->temperature = $temperature;
$this->humidity = $humidity;
$this->pressure = $pressure;
$this->notifyObserver();
}
}
// Cette classe observe WeatherStation
class currentWeatherDisplay
{
private $temperature = 'non définit';
private $humidity = 'non définit';
private $pressure = 'non définit';
private $appareil;
public function __construct($appareil)
{
$this->appareil = $appareil;
$this->display();
}
public function update($temperature, $humidity, $pressure)
{
$this->temperature = $temperature;
$this->humidity = $humidity;
$this->pressure = $pressure;
$this->display();
}
public function display()
{
echo "<br/>{$this->appareil} - Conditions actuelles : {$this->temperature}°C et {$this->humidity}% d'humidité<br/>";
}
}
$weatherStation = new WeatherStation();
$currentDisplay1 = new currentWeatherDisplay('Ecran principal');
$currentDisplay2 = new currentWeatherDisplay('Ordinateur');
$currentDisplay3 = new currentWeatherDisplay('Tablette');
$weatherStation->addObserver($currentDisplay1);
$weatherStation->addObserver($currentDisplay2);
$weatherStation->addObserver($currentDisplay3);
$weatherStation->setMeasurements(25, 65, 1012.2);
$weatherStation->setMeasurements(27, 67, 1014.2);