Previously, I talked about patterns where you were unlikely to implement them yourself, since they are now considered part of the infrastructure that goes with a modern language. The publish/subscribe model isn’t quite ready to be described as infrastructure, but it’s getting close. So, here are two patterns I don’t honestly think it’s worth knowing. Here, it’s not so much that the patterns are bad, just that you’re better off understanding and using the publish/subscribe model. Here’s how the pub/sub model works:
- Participants are called services.
- They do not communicate directly with one another, but through messages/events raised by one and consumed by others.
- Each service can register its interest in the messages for any other participant.
- However, no service references any other participant. Instead, messages are placed on a message bus, and consumed by means of method calls on the destination object or objects.
- In asynchronous scenarios, when an event is raised, it is placed on a queue. The service consumes the messages in the order they were sent, but not necessarily on the same box and definitely with no guarantee of exactly when it happens.
Now, here’s some implementations of the pub/sub pattern you can use for free:
Of these, each has their advantages. Personally, I dislike .NET events because getting a message from one service to another pretty much requires you to be able to reference both objects, which cuts down on the decoupling that pub/sub gives you. Of the others:
- nServiceBus is most appropriate for long running processes, and those that split across machines.
- retlang is preferable when you’ve got low-latency requirements, and you’re happy with everything running on one machine.
- Udi Dahan’s code is incredibly short, and appropriate when you don’t feel the need for a more complex solution. It is synchronous and single threaded, which can be a blessing or a curse depending on your context.
Now, I was promising that I’d talk about GoF patterns, so let’s get back to it:
One object listens to events/messages pushed out by another. Any consuming service in a pub/sub framework could be considered an observer, as could anything that listens to .NET events. However, it’s very generality means that it’s not really that useful as a concept.
A term used to describe an object that is used when services don’t directly communicate with one another. In the publish/subscribe model, this is the message bus.
The Observer and Mediator patterns should not be implemented directly by your code. If it looks like one or the other might be appropriate, you should consider the use of a publish/subscribe framework.
NOTE: I’m going to have to revise this in light of Rx, a useful framework that targets the observer pattern directly.