You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The [observer pattern](https://en.wikipedia.org/wiki/Observer_pattern) allows a type instance to "publish" events to other type instances ("observers") who wish to be updated when a particular event occurs.
4
+
5
+
## Implementation
6
+
7
+
In long-running applications—such as webservers—instances can keep a collection of observers that will receive notification of triggered events.
8
+
9
+
Implementations vary, but interfaces can be used to make standard observers and notifiers:
10
+
11
+
```go
12
+
type (
13
+
// Event defines an indication of a point-in-time occurrence.
14
+
Eventstruct {
15
+
// Data in this case is a simple int, but the actual
16
+
// implementation would depend on the application.
17
+
Dataint64
18
+
}
19
+
20
+
// Observer defines a standard interface for instances that wish to list for
21
+
// the occurrence of a specific event.
22
+
Observerinterface {
23
+
// OnNotify allows an event to be "published" to interface implementations.
24
+
// In the "real world", error handling would likely be implemented.
25
+
OnNotify(Event)
26
+
}
27
+
28
+
// Notifier is the instance being observed. Publisher is perhaps another decent
29
+
// name, but naming things is hard.
30
+
Notifierinterface {
31
+
// Register allows an instance to register itself to listen/observe
32
+
// events.
33
+
Register(Observer)
34
+
// Deregister allows an instance to remove itself from the collection
35
+
// of observers/listeners.
36
+
Deregister(Observer)
37
+
// Notify publishes new events to listeners. The method is not
38
+
// absolutely necessary, as each implementation could define this itself
39
+
// without losing functionality.
40
+
Notify(Event)
41
+
}
42
+
)
43
+
```
44
+
45
+
## Usage
46
+
47
+
For usage, see [observer/main.go](observer/main.go) or [view in the Playground](https://play.golang.org/p/cr8jEmDmw0).
0 commit comments