+ 2
Suggestions on Implemented observer pattern
Hi Please find below code I have implemented for observer design pattern: https://code.sololearn.com/cY7MaU8bNbtc Can anyone suggest me any improvements on the same? One I know and that is like not to define class member functions as inline. Any other ? Please feel free to share your view. Additionally, child class has mechanism to implement a observer pattern like add observer and remove observers. Is there a way to make it generalized implementation as I think that each class which I want to make as observer will have these code as repeated. Thanks in advance..!
3 Respostas
+ 3
What you have is a violation of the single responsibility principle for your Child class (which is now responsible for doing kid stuff (like getting injured) and to provide the publish-subscribe infrastructure).
As suggested before, refactor the observer pattern infrastructure out into classes Observer and Observable. The observer is much interested in the observed object's state, so be sure to pass it to the observer.
For example:
https://code.sololearn.com/c5M7nJ3dmgp4
As for generalising the observers, well, any observer can in principle do whatever with the information. If you feel that all observers have a common response, of course, you can create abstract classes to refactor out commonalities and use calls to abstract methods, implementation details of which are left to concrete classes.
+ 2
You try to make an abstract
Observer class and abstract subject class
Then make a base class which implements both observer and subject
And make the rest of your classes from the base class
+ 2
Thanks Raul Ramirez and Ani Jona 🕊