-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver-pattern.php
More file actions
92 lines (79 loc) · 2.34 KB
/
observer-pattern.php
File metadata and controls
92 lines (79 loc) · 2.34 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
79
80
81
82
83
84
85
86
87
88
89
<?php
/**
* Observer Pattern
*
* Definition:
* The Observer Pattern is a behavioral design pattern in which an object (the Subject) maintains a list of dependents (Observers) and notifies them of any state changes, usually by calling one of their methods.
*
* Benefits:
* - **Loose Coupling:** The subject and observers are loosely coupled, making the system more flexible and easier to maintain.
* - **Scalability:** New observers can be added without modifying the subject.
* - **Better Code Organization:** Separates concerns by allowing the subject to focus on state changes and observers to focus on handling updates.
*/
/**
* Observer Interface
*
* Defines a contract for observers that need to receive updates.
*/
interface Observer {
/**
* Method to be called when the subject sends an update.
*
* @param string $message The message to be received by the observer.
*/
public function update(string $message);
}
/**
* Concrete Observer - User
*
* Implements the Observer interface to receive updates from the subject.
*/
class User implements Observer {
/**
* Receives an update message from the subject.
*
* @param string $message The message sent by the subject.
*/
public function update(string $message) {
echo "Received: $message\n";
}
}
/**
* Subject - NewsChannel
*
* Manages a list of observers and notifies them of any updates.
*/
class NewsChannel {
/**
* @var array List of observers subscribed to updates.
*/
private array $observers = [];
/**
* Attach an observer to the channel.
*
* @param Observer $observer The observer to attach.
*/
public function attach(Observer $observer) {
$this->observers[] = $observer;
}
/**
* Notify all observers with a message.
*
* @param string $message The message to send to observers.
*/
public function notify(string $message) {
foreach ($this->observers as $observer) {
$observer->update($message);
}
}
}
// Creating the subject (News Channel)
$channel = new NewsChannel();
// Creating observers (Users)
$user1 = new User();
$user2 = new User();
// Attaching observers to the news channel
$channel->attach($user1);
$channel->attach($user2);
// Sending a notification to all observers
$channel->notify('Hello, World!');