Observer design pattern (also known as Publish/Subscribe) is a software design pattern, used when we are building a system where the state of one object affects the state of other objects. It is a key part of model-view-controller architectural pattern.
In a traditional MVC ( Model-View-Controller ) architecture, a model is a subject and a view is an observer. A view is notified when a model changes and responds accordingly. When the subject sends observers detailed information about what has changed, indiscriminately, this is known as the push model of the Observer pattern. When a subject sends only minimal information to its observers must ask for details explicitly, this is known as the pull model of the Observer pattern.
Ruby provides a simple mechanism to implement this design pattern using the Observable module. In this mechanism, the Notifier class uses the Observable module, which provides the methods for managing the associated observer objects.
The observable object must:
- assert that it has #changed
- call #notify_observers
Public Instance Methods
Instance methods are methods that are called on an instance of a class. We can use the below methods while using Observer instances.
- add_observer(observer, func=:update)
Adds observer as an observer on this object, so that it will receive notifications.
Set the changed state of this object. Notifications will be sent only if the changed state is true.
Returns true if this object’s state has been changed since the last notify_observers call.
Return the number of observers associated with this object.
Remove observer as an observer on this object so that it will no longer receive …