Saturday, November 29, 2014

Design Pattern : Observer Design Pattern


Type : Behavioral Design Pattern

Summary

In Observer Design Pattern, an Object called subject maintains one to many relationship with Observers, so that once the state of the Subject changes it can automatically inform Observers registered with the subject.

Advantage

An Object(Subject) can notify other Objects(Observer) without being tightly coupled with Observer and depend on Observer Class.

Disadvantage

Due to the indirect communication between Subject and Observer's it can lead to performance issues.


Important Points

Multiple Subscribers for a Subject.
Subjects know its Subscribers.
Generally the Subject triggers the method that updates Observers.
New Observers can be added to the System with minimal changes.

Details

Following are different participants in Observer Pattern

Subject(Interface)

› Keeps track of its observers

› Provides an interface for attaching and detaching Observer objects

Observer(Interface)

› Defines an interface for update notification

ConcreteSubject

› The object being observed

› Sends a notification to its observers when its state changes

ConcreteObserver

› The observing object

› Stores state that should stay consistent with the subject's

› Implements the Observer update interface to process any changes in Subject
Simple Example

Let's think about a simple Mobile APP which is all about Questions-Answers Application. When the User selects a particular answer, based on whether the answer is right or wrong we have to update many UI components. For instance if correct we have to update the Points, and also we have to update the counts for correct/wrong answers etc.



Class Diagram















No comments :

Post a Comment