Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP Class being an Observerable and Observer

I have a problem whereby I have a class Item, which has a list of Subitems. 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.

like image 566
Nick Avatar asked Oct 21 '22 13:10

Nick


2 Answers

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, Observables don't want to know the details about their Observers (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

like image 75
Fuhrmanator Avatar answered Oct 29 '22 14:10

Fuhrmanator


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.

like image 26
RMachnik Avatar answered Oct 29 '22 13:10

RMachnik