I’m starting to read about design patterns and trying to apply them to some coding. I’ve read about the observer pattern and think it would be a most useful one to make use of.
My two questions are these:
1) If I want my object to be both an observer and a subject, is it simply a question of making it inherit from both the observer and the subject class? Say I have several units in an army, and I want them to quickly send local updates to each other. Does it work as I have described, or does it necessitate another pattern completely?
2) If an object needs to communicate with types of many a different nature (say a general needs to communicate with his units, with the faction leader, etc.), does the observer pattern still work? I guess it would just be a question of implementation, but I don’t know…
Normally, the observer patterns is about applying a layered approach: a higher level object controls a lower level one and it is an observer, so it can react on changed status of the lower level object.
In your case, you want communication between peers and you want all objects to know each other, so observer doesn’t add real value.
Observer would work better if there would be a controlling object on top of the units that knows what to do on updates.
Of course, it is up to you to decide wheter this would work better in your case.
BTW, check boost signals as an implementation for your observer