Friday, 7 January 2011

Observer Design Pattern

Observer Pattern Comes Under the Behavioral Patterns.


// Observer interface is available under java.util package.
// This interface has update method which gets called as soon
//as the status of Observable class changes and it
//notifies the observers.
package oops.observer;
import java.util.Observable;
import java.util.Observer;
public class ProjectLead implements Observer{
@Override
public void update(Observable arg0, Object arg1) {
System.out.println(this.getClass().getSimpleName() +" received updates from    "+arg0.getClass().getSimpleName() +" "+arg1);
}
}



//Another observer for project development.
package oops.observer;
import java.util.Observable;
import java.util.Observer;
public class Client implements Observer {
@Override
public void update(Observable arg0, Object arg1) {
System.out.println(this.getClass().getSimpleName() +" received updates from "+arg0.getClass().getSimpleName() +" "+arg1);
}
}



//Developer : does the regular work and notifies observers.
//Observable class belongs to java.util package and has two
// important methods : setChanged and notifyObservers
package oops.observer;
import java.util.Observable;
public class Developer extends Observable {
private String name;
public Developer(String name){
this.name = name;
}
public void doRegularWork() {
workOnAssignments();
sendUpdates();
}
private void workOnAssignments() {
// TODO :
}
private void sendUpdates() {
setChanged();
notifyObservers(name);//NOTE : notifyObservers without argument is also available!
}
}



//ProjectDevelopment : A framework to track the development progress.
package oops.observer;
public class ProjectDevelopment {
public static void main(String[] args) {
Developer dev = new Developer("Anuja");
ProjectLead lead = new ProjectLead();
Client client = new Client();
dev.addObserver(lead);
dev.addObserver(client);
dev.doRegularWork();
}
}

2 comments:

  1. I think Anuja, if these codes are also complemented by their Class/Sequence Diagrams, then they will act as a good 'summary'.

    Also if you can explain Model-View-Controller(the way you have used it) then I'd like to read it! I think I still haven't understood MVC completely.

    [These are just suggestions and not advise :) ]

    ReplyDelete
  2. Thanks Mukul for the suggestion. I'll try to use explanatory diagrams. Stay tuned with further posts....

    ReplyDelete