Tuesday, March 8, 2016

Design Pattern - 2 Observer Pattern

The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated successfully.

Observer pattern has a Subject to which Observers listen to. It is similar to a subscriber-enewspaper relationship. Whenever a newspaper (subject) is published, the subscribers(observers) are notified.
Also similar like a button in a page whose listeners perform different operations based on the button action.

Design principle: Strive for loosely coupled designs between objects that interact.

Observable is a class in java.util. package where the observer pattern is implemented.

Typically, the Subject interface or Observable class has methods to add an observer, remove an observer and notifyObservers().The subject maintains a list of observers.The subject is unaware when a new observer is added.
public SubjectImpl implements Subject {
  private List observerList ;
  public void addObserver(Observer observer){ observerList.add(observer); }
  public void removeObserver(Observer observer { // code to remove from observerlist; }
  public void notifyObservers() {  // Iterate over list of observerList and notify the data change }
}

The Observer interface or class implementing observer interface will register or add itself to the  Subject. The subject reference is maintained in the observer class.

public ObserverImpl implements Observer{
 private Subject subject;
 public ObserverImpl(Subject subjectarg){
   this.subject = subjectarg;
   subject.addObserver(this);
 }

}

The order of notification to observers CANNOT be guranteed by subject.
Swing uses heavy usage of Observer pattern.

Design principles so far:
Design Principle 1: Identify the parts of the application that can vary and separate them from what stays the same. Encapsulate what varies.

Design Principle 2: Program to an interface, not an implementation.

Design Principle 3: Favor composition over inheritance.


Design principle 4: Strive for loosely coupled designs between objects that interact. 





No comments: