views:

107

answers:

2

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...

+1  A: 

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?

Yup.

2) If an object needs to communicate with types of many a different nature does the observer pattern still work?

Yup.

Just in case you switch to .NET/C# there's a nice library for reacting to/processing events from observables: Rx http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx.

Mau
+1  A: 

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

stefaanv
Thanks. That is what I was thinking as well, from the limited knowledge I have. However, having each unit have a collection of pointers to all other units on the same level just doesn't seem right to me.
Kristian D'Amato
The solution could be to create an army-object that contols your units, but the downside could be that part of the logics is in the army class and the other part is in the unit classes. It is still your decision.
stefaanv