Go Patterns

How to Implement Mediator Pattern in Go

Behavioral Design Patterns in Go

Pavel Fokin
3 min readJun 6, 2022
Mediator Pattern in Go
Mediator Pattern in Go

Sometimes we have a bunch of objects that need to interact with each other. A number of objects can be large and their interactions can have complex logic.

Mediator pattern helps to organize such cases.

  • Mediator lets keep loose coupling and don’t let objects have direct communication.
  • Mediator keeps the interaction logic and allows to change it independently.

Let’s look for an example!

A chat

For example, we have a bunch of Users and they want to interact with each other.

  • A User can send a message to another User.
  • A User can send a message to all Users.
  • Some Users can be unavailable for messaging.

So we introduce a Chat object that keeps this logic and organizes communication.

Gophers chat

User type

Firstly, we will introduce a User type. It will have a Name and store Messages.

User type

Chat type

Then we need a Chat type. It will have a method to Add a User and keep information about Users in the Chat. This is our Mediator.

Chat type

Interaction logic

Now, let’s extend our Chat with interaction logic.

  • Say(to User, msg string) - sends a message to the specific User and handles an error if the User is not in the Chat.
  • SayAll(msg string) - sends a message to the all available Users.
Interaction logic

Usage Example

Now, we gather all pieces together to see how it works.

Main function

Conclusion

Mediator pattern is a good example of encapsulation logic into separate entity. It’s a complement to the Observer pattern. In real world applications though the logic can grow a lot, and turn this into God object antipattern.

Happy coding!

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

More reading

If you like this article you can be interested in the following.

Originally published at https://pavelfokin.dev.

--

--