I want to implement the observ开发者_高级运维er pattern and I want class X to observe updates in classes A and B.
X is derived from the abstract base class XObs which has the update() function taking an enum as parameter of what has happened.
The logical problem here is that X needs to know which of A and B sent the update and X cannot determine that from the enum parameter.
What are the pros/cons of adding another parameter to update() which tells which of A and B sent the update? What other ways are possible to solve this? (I rather not create a base class for A and B and send a this pointer in the update() as A and B are quite different.)
Thanks,
Tomas
The common base class for a and b doesnt have to have any distinct functionality - it just needs to be used to express the fact that A and B are Observable. In this sense A and B are not 'quite different', they are the same.
I see the following options:
- make both A and B implement a common Observable base class (and pass them as parameters to
update()
- the problem is, you need to downcast inupdate()
to detect whether the parameter is of A or B, which makes the solution fragile - add some sort of type flag parameter to
update()
- this is fairly similar to the previous one, only less object oriented - templatize the Observer / Observable implementation - I haven't worked this out fully in my head (and I don't have a C++ IDE to verify it), but I believe this way you can have two overloads of
update()
with different (A and B) type parameters, thus the handling is separated and straightforward, so this would be my preferred option
精彩评论