-
Notifications
You must be signed in to change notification settings - Fork 1
/
ObserverPattern.php
119 lines (87 loc) · 2.49 KB
/
ObserverPattern.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
abstract Class abstractAnimalObserver {
abstract function updateSleepCount(Abstractanimal $animal_in);
abstract function updateEatCount(Abstractanimal $animal_in);
}
abstract Class abstractAnimal {
abstract function attach(AbstractAnimalObserver $observer_in);
abstract function detach(AbstractAnimalObserver $observer_in);
abstract function notifySleeps();
abstract function notifyEats();
}
Class animalObserver extends abstractAnimalObserver {
//global counts of eats and sleeps
protected $sleeps = 0;
protected $eats = 0;
protected static $lineBreak = "<br>";
public function __construct() {
}
public function updateSleepCount(abstractAnimal $animal) {
$this->sleeps++;
printf("Total Sleeps so far: ".$this->eats.self::$lineBreak);
printf("Your Sleeps so far: ".$animal->getSleeps().self::$lineBreak);
}
public function updateEatCount(abstractAnimal $animal) {
$this->eats++;
printf("Total Eats so far: ".$this->eats.self::$lineBreak);
printf("Your Eats so far: ".$animal->getEats()." ".$animal->getName().self::$lineBreak);
}
}
class animal extends AbstractAnimal {
private $observers = array();
private $mySleeps = 0;
private $myEats = 0;
private $name = null;
function __construct($name) {
$this->name = $name;
}
function attach(AbstractAnimalObserver $observer_in) {
$this->observers[] = $observer_in;
}
function detach(AbstractAnimalObserver $observer_in) {
foreach($this->observers as $okey => $oval) {
if ($oval == $observer_in) {
unset($this->observers[$okey]);
}
}
}
function notifySleeps() {
foreach($this->observers as $obs) {
$obs->updateSleepCount($this);
}
}
function notifyEats() {
foreach($this->observers as $obs) {
$obs->updateEatCount($this);
}
}
function updateMySleeps() {
$this->mySleeps++;
$this->notifySleeps();
}
function getSleeps() {
return $this->mySleeps;
}
function updateMyEats() {
$this->myEats++;
$this->notifyEats();
}
function getEats() {
return $this->myEats;
}
function getName() {
return $this->name;
}
}
$observer = new animalObserver;
$person = new animal("Mark");
$cat = new animal("Rufus");
$person->attach($observer);
$cat->attach($observer);
$person->updateMyEats();
$cat->updateMyEats();
$person->updateMyEats();
$person->updateMyEats();
$cat->updateMyEats();
$person->detach($observer);
$cat->detach($observer);