The Observer Pattern ↩
RoboFont is built using what is known as the Observer Pattern, a distributed event-handling system which makes communication between objects very clean and clear.
Interface and objects talking directly
In an application we have an interface, and we have objects: a font, or kerning, or something like that. The interface shows the user what’s inside the object.
In simple scripts and tools, we’ll often have the interface talking directly to the object and the object talking directly to the interface:
This makes sense when we have a diagram with only two arrows. But when we start building more complex tools, we’ll quickly end up with something like this:
…and it becomes difficult to change the interface or the objects without breaking things, because each one knows about the internals of the other.
Communicating through a dispatcher
The Observer Pattern introduces a ‘dispatcher’ between the object and the interface. Objects can broadcast messages to the outside world. When the object changes, it communicates that to the dispatcher rather than talking to the interface directly.
One of the advantages of this system is that the object doesn’t need to know about the outside world – it can do it’s own thing, and the code can stay very clear and concise, without calls to the interface. The interface tells the dispatcher that it wants to be informed when the object changes; then when the object does change, the dispatcher takes care of communicating it to the interface.
Another advantage is that it allows a one-to-many relationship: the dispatcher can communicate with different parts of the interface. Imagine an application with several views, all of them subscribed to the dispatcher – whenever the font changes, the views automatically know about it and update themselves. The object doesn’t need to know that there’s a window open, or about the settings of a particular view, etc.
And most importantly: the developer is free to add and remove parts of the interface without breaking anything.
Based on Building Apps, Tal Leming’s presentation at RoboThon 2012.