I have a problem whereby I have a class Item
, which has a list of Subitem
s. When a child item has been changed or deleted, I need the parent Item to know about it.
I was thinking that the Observer pattern would come in handy here. But does it make sense for an Item class to both extend extend Observerable
and implement Observer
?
Cheers.
Yes it makes sense sometimes to have an observer also be observed.
Ask yourself why you want to apply the pattern, however. Observing just to give updates might be more complicated to debug, compared to just updating directly, e.g., the child calls his parent when he updates.
Generally, Observable
s don't want to know the details about their Observer
s (decoupling, information hiding) so that you can make virtually any class an Observer
. If that is what you need, then the pattern is good for you. If not, then adding this may result in needless complexity (harder to understand and debug the code).
Edit (I had this backwards): Do your child (Observable) items already know all the details about their parents (Observer)? If they do, then using Observer
might be over-design. If children don't want to know the details of their parent, then Observer
could be useful.
When making observers be observable, watch out for cycles https://stackoverflow.com/a/964820/1168342
Your argumentation and situation make sense to use Observer Design pattern. There is very handfull article about Oberver design pattern. There is also very simple example in java so there is no sense to paste it here. Please look on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With