View on observer design pattern implementation | SoloLearn: Learn to code for FREE!

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?

5/25/2020 4:36:33 PM

Ketan Lalcheta

3 Answers

New Answer

+2

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 ?

+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.

+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);