-
Notifications
You must be signed in to change notification settings - Fork 0
/
observer.php
71 lines (68 loc) · 1.69 KB
/
observer.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
<?php
class Subject{
private $observers;
private $state;
public function __construct(){
$this->observers = new SplDoublyLinkedList();
}
public function getState():int{
return $this->state;
}
public function setState(int $state){
$this->state=$state;
$this->notifyObservers();
}
public function attach(Observer $observer){
$this->observers->push($observer);
}
public function notifyObservers(){
for($this->observers->rewind();$this->observers->valid();$this->observers->next()){
$ob=$this->observers->current();
$ob->update();
}
}
}
abstract class Observer{
protected $subject;
abstract protected function update();
}
class BinaryObserver extends Observer{
public function __construct(Subject $subject){
$this->subject=$subject;
$this->subject->attach($this);
}
public function update(){
echo "Binary String:".decbin($this->subject->getState())."\r\n";
}
}
class OctalObserver extends Observer{
public function __construct(Subject $subject){
$this->subject=$subject;
$this->subject->attach($this);
}
public function update(){
echo "Binary String:".decoct($this->subject->getState())."\r\n";
}
}
class HexObserver extends Observer{
public function __construct(Subject $subject){
$this->subject=$subject;
$this->subject->attach($this);
}
public function update(){
echo "Binary String:".dechex($this->subject->getState())."\r\n";
}
}
class ObserverpatternDemo{
public function __construct(){
$suject = new Subject();
new BinaryObserver($suject);
new OctalObserver($suject);
new HexObserver($suject);
echo "First state change: 15\r\n";
$suject->setState(15);
echo "Second state changet: 10\r\n";
$suject->setState(10);
}
}
new ObserverpatternDemo();