Home
Core Java
Java
JDBC
Servlets
JSP
EJB
JMS
Struts
Spring
Hibernate
JSF
RMI
CORBA
J2ME
Performance
Tomcat
Weblogic
Design Patterns
Junit
XML
UML
DB2 & SQL
ANT
Free Gift
Contact Us

XML RSS
What is this?
Add to My Yahoo!
Add to My MSN
Add to Google
 

Behavorial Pattern

Observer Pattern

Your Ad Here

Creational patterns Structural patterns Behavioral pattern J2EE patterns
Abstract Factory Adapter  Chain of Responsibility
MVC 
Builder Bridge  Command  Business Delegate
Factory method Composite  Interpreter  Composite Entity
Prototype Decorator  Iterator  Data Access Object
Singleton FaƧade
Mediator  Front Controller

Flyweight  Memento  Intercepting Filter

Proxy  Observer  Service Locator


State  Transfer Object


Strategy 


Template Method



Visitor 

Observer Pattern



Define Observer pattern
One object changes state, all of its dependents are updated automatically.

Where to use & benefits
One change affects one or many objects.
Many object behavior depends on one object state.
Need broadcast communication.
AKA “Publish-Subscribe”.
Maintain consistency between objects
keep classes from becoming too tightly coupled, which would hamper reusability.

Related patterns include
  • Singleton, which is used to make observable object unique and accessible globally.
  • Mediator, which is used to encapsulate updated objects.

Your Ad Here
Example of Observer pattern
Observer pattern is often used in GUI application. For example, defining a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically, like stock change affecting many data or diagram updated accordingly.

Java API provides a built-in interface Observer and class Observable for use.

To show how observer pattern works, two windows have been created. One is for user input; another is for display. When the data has been entered in the textfield, another window gets the message and display it with a dialog. The private inner classes have been used in this example.

import javax.swing.*;
import java.awt.event.*;
import java.util.*;

class DisplayForm extends JFrame {
    InputFormObserver input = new InputFormObserver();
    InputForm inputForm ;
    Observable obsInput;
    JTextField display;
    //...
    public DisplayForm() {       
        addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                  System.exit(0);
        }});
        inputForm = new InputForm();
        obsInput = inputForm.getInputInfo();
        obsInput.addObserver(input);
   
        display = new JTextField(10);
            display.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                   
               }
           });
        getContentPane().add(display);
        setTitle("Observer form");
        setSize(200,100);
        setLocation(200,100);
        setVisible(true);
    
    }
   
    private class InputFormObserver implements Observer {
         public void update(Observable ob, Object o) {
             doSomeUpdate();
             if (obsInput.countObservers()>0)
                    obsInput.deleteObservers();
             obsInput = inputForm.getInputInfo();
             obsInput.addObserver(input);
         }
        
     }
     public void doSomeUpdate() {
            display.setText(inputForm.getText());
                    JOptionPane.showMessageDialog(DisplayForm.this,
                            "This form has been updated");
    }
    public static void main(String args[]) {
        DisplayForm df = new DisplayForm();
    }
}
class InputForm extends JFrame {
    public InformDisplay inform = new InformDisplay();
    //...
    JTextField input= new JTextField(10);
       
    public InputForm() {
        JPanel panel= new JPanel();
        input.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    inform.notifyObservers();
               }
           });
        panel.add(new JLabel("Enter: "));
        panel.add(input);
        addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e) {
                      System.exit(0);
        }});
        getContentPane().add(panel);
        setTitle("Observable form");
        setSize(200,100);
        setVisible(true);
    }
    public Observable getInputInfo() {
        return inform;
    }
   
    public String getText() {
        return input.getText();
    }
   
    private class InformDisplay extends Observable {
        public void notifyObservers() {
            setChanged();
            super.notifyObservers();
        }
        public String getChange() {
            return input.getText();
        }
    }
    //...
}
java DisplayForm

Two windows will come up:
one for user input, the other for observing user input.
Enter data in the input window, a dialog box from other window shows up
and the input data has been shown in the other window.

Your Ad Here




footer for Observer Pattern page