0

View on observer design pattern implementation

Hi I implemented observer design pattern as below.... https://code.sololearn.com/chZh6PDau64w Is it correct or not ? Is implementation is best or there is some chance of betterment?

25th May 2020, 4:36 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Respuestas
+ 3
Okay Schindlabua .. got it.... Another issue is that I am myself not convinced to use observer pattern in this case.... Something below would also work as we just need different objects only: https://code.sololearn.com/cnCnbu7r0Fj0/?ref=app Does this trial of different objects of same class will not suffice problem? I mean do we need more than one class's object or same class's more than one object for observer design pattern? If different class are required, does those need to be inherited from same parent class ?
25th May 2020, 8:47 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
The logic seems sound, but you may run into trouble if an observer runs out of scope and is destroyed. You may create some dangling pointers. Maybe a vector filled with std::weak_ptr<T> is preferrable over plain pointers here? Or references.
25th May 2020, 5:36 PM
Schindlabua
Schindlabua - avatar
+ 1
The observer pattern is very flexible, both of your solutions are fine. A cool thing about ovservers are that you can make anything talk to anything, so if I just have two classes talking to each other I might not use it. Well, maybe. Maybe not. You might be able to come up with a solution where classes don't need to derive from a base class, with std::function for example. But my C++ is not good enough to make that work. Anyway deriving is definitely easiest. How about this: template<class T> class observer { public: virtual dispatch(T& value) = 0; } template<class T> class observable { vector<observer<T>> observers; public: Observable () : observers() { } add_observer(observer<T>& o) { observers.push_back(o); } dispatch(T& value) { for(auto o : observers) o.dispatch(value); } } and then you can derive as needed. class clsStudent : Observable<int> { } class clsGuardian : Observer<int> { } student.add_observer(guardian);
26th May 2020, 7:05 AM
Schindlabua
Schindlabua - avatar
0
shubham kumar don't spam thread of q/a.... If it is not relevant to the question asked , don't post unnecessarily here
21st Jul 2020, 6:19 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
21st Jul 2020, 1:03 AM
shubham kumar
shubham kumar - avatar