Go Patterns

How to Implement Observer Pattern in Go

Behavioral Design Pattern in Go

Pavel Fokin
Mindware Engineering

--

Observer Pattern

The Observer Pattern defines a one-to-many dependency between Notifier and Observers. When Notifier changes its state all Observers are notified with Events.

This pattern can be used in the event-driven code. When one parts of the code have to react on changes in another part.

Basic Types and Interfaces

We will start with defining type for Event.

Event Type

Next step will be to write an interface for Observer.

Observer Interface

Third step is to implement interface for the Notifier.

This interface has 3 methods:

  • Register(Observer)
  • Unregister(Observer)
  • Notify(Event)
Notifier Interface

Implement Concrete Types

Now let’s implement concrete Observer using our Observer interface.

Observer Implementation

Next step is to define Notifier for our Notifier interface.

Notifier Implementation

Usage Example

Get all things together and write the main function.

Main Function

And output will be

# Output
➜ go-patterns go run ./behavioral/observer
observer 1 recieved event 1
observer 2 recieved event 1
observer 1 recieved event 101
observer 2 recieved event 101
observer 1 recieved event 9999
observer 2 recieved event 9999

Conclusion

Implementing a basic Observer Pattern is not a hard task, and it is often implemented in the event-driven. In those systems, the Notifier is usually named a "stream of events".

Happy coding!

Code examples can be found in my GitHub repo pavel-fokin/go-patterns.

Originally published at https://pavelfokin.dev.

--

--