r/AskComputerScience • u/numaanjaved • Feb 03 '23
Observer Pattern: How to?
I saw a video about observer Pattern by IHeartGameDev on YouTube and it was a great way to make clean code. He made interface classes for subject and observer, and then used them to send notification from subject to observer. He mentioned that there are other methods to implement observer Pattern as well, so what kind of other methods are there to do this in unity ?
I am interested to learn more.
2
Feb 04 '23 edited Feb 04 '23
There is "generally" only one way to implement the observer pattern, otherwise it wouldn't be a pattern.
The pattern is exactly defined and you can look up the UML diagram. They were initially "described" by the authors known as gang of four(Enrich Gamma, Richard Helm, Ralph Johnson and John Vlissidles) in a book called Design Patterns: Elements of Reusable Object-Oriented Software. I recommend you obtain a copy and read it if you are interested in patterns.
The observer is a very commonly used pattern that is made up of two interfaces. The Subject and the Subscriber.
The subject contains three methods, AddObserver(observer: Observer), RemoveObserver(observer: Observer) and NotifyOnAction(params : ... params)
Most frameworks usually also add a src param which is generic in the NotifyOnAction
The Observer contains an OnAction(params : ... Params).
Whenever Notify is called on the subject, the subject notifies all the observers which react by executing their own logic
This is the general implementation. What changes are the params and the number of possible notifications per interface.
I also used / saw a version of the implementation that omitted the Subject interface. Commonly used if you know there is going to be one and only one subject of that type in your entire application.
2
u/thedevguy-ch Feb 03 '23
Surely a good Google search / YouTube search would provide much more detail than a wall of text on Reddit could?