Java/Design Pattern/Observer Pattern

Материал из Java эксперт
Перейти к: навигация, поиск

A simple demo of Observable and Observer

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.util.Observable; import java.util.Observer; /**

* A simple demo of Observable->Observer
* 
* @author Ian Darwin
* @version $Id: ObservDemo.java,v 1.3 2003/12/29 19:52:22 ian Exp $
*/

public class ObservDemo extends Object {

 MyView view;
 MyModel model;
 public ObservDemo() {
   view = new MyView();
   model = new MyModel();
   model.addObserver(view);
 }
 public static void main(String[] av) {
   ObservDemo me = new ObservDemo();
   me.demo();
 }
 public void demo() {
   model.changeSomething();
 }
 /** The Observer normally maintains a view on the data */
 class MyView implements Observer {
   /** For now, we just print the fact that we got notified. */
   public void update(Observable obs, Object x) {
     System.out.println("update(" + obs + "," + x + ");");
   }
 }
 /** The Observable normally maintains the data */
 class MyModel extends Observable {
   public void changeSomething() {
     // Notify observers of change
     setChanged();
     notifyObservers();
   }
 }

}



 </source>
   
  
 
  



Implementing a Simple Event Notifier

   <source lang="java">
 

import java.util.Observable; import java.util.Observer; class MyModel extends Observable {

 public synchronized void setChanged() {
   super.setChanged();
 }

} public class Main {

 public static void main(String[] argv) throws Exception {
   MyModel model = new MyModel();
   model.addObserver(new Observer() {
     public void update(Observable o, Object arg) {
     }
   });
   model.setChanged();
   Object arg = "new information";
   model.notifyObservers(arg);
 }

}


 </source>
   
  
 
  



Observable and observer

   <source lang="java">
 

import java.util.Observable; import java.util.Observer; public class MessageBoard extends Observable {

 private String message;
 public String getMessage() {
   return message;
 }
 public void changeMessage(String message) {
   this.message = message;
   setChanged();
   notifyObservers(message);
 }
 public static void main(String[] args) {
   MessageBoard board = new MessageBoard();
   Student bob = new Student();
   Student joe = new Student();
   board.addObserver(bob);
   board.addObserver(joe);
   board.changeMessage("More Homework!");
 }

} class Student implements Observer {

 public void update(Observable o, Object arg) {
   System.out.println("Message board changed: " + arg);
 }

}


 </source>
   
  
 
  



Observer Pattern - Example in Java

   <source lang="java">
 

/* Software Architecture Design Patterns in Java by Partha Kuchana Auerbach Publications

  • /

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Calendar; import java.util.Date; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; public class MonthlyReport extends JFrame implements Observer {

 public static final String newline = "\n";
 private JPanel panel;
 private JLabel lblTransactions;
 private JTextArea taTransactions;
 private ReportManager objReportManager;
 public MonthlyReport(ReportManager inp_objReportManager) throws Exception {
   super("Observer Pattern - Example");
   objReportManager = inp_objReportManager;
   // Create controls
   panel = new JPanel();
   taTransactions = new JTextArea(5, 40);
   taTransactions.setFont(new Font("Serif", Font.PLAIN, 14));
   taTransactions.setLineWrap(true);
   taTransactions.setWrapStyleWord(true);
   //Create Labels
   lblTransactions = new JLabel("Current Month Transactions");
   //For layout purposes, put the buttons in a separate panel
   JPanel buttonPanel = new JPanel();
   buttonPanel.add(lblTransactions);
   buttonPanel.add(taTransactions);
   Container contentPane = getContentPane();
   contentPane.add(buttonPanel, BorderLayout.CENTER);
   try {
     UIManager.setLookAndFeel(new WindowsLookAndFeel());
     SwingUtilities.updateComponentTreeUI(MonthlyReport.this);
   } catch (Exception ex) {
     System.out.println(ex);
   }
   setSize(400, 300);
   setVisible(true);
   objReportManager.register(this);
 }
 public void refreshData(Observable subject) {
   if (subject == objReportManager) {
     //get subject"s state
     String department = objReportManager.getDepartment();
     lblTransactions.setText("Current Month Transactions - "
         + department);
     Vector trnList = getCurrentMonthTransactions(department);
     String content = "";
     for (int i = 0; i < trnList.size(); i++) {
       content = content + trnList.elementAt(i).toString() + "\n";
     }
     taTransactions.setText(content);
   }
 }
 private Vector getCurrentMonthTransactions(String department) {
   Vector v = new Vector();
   FileUtil futil = new FileUtil();
   Vector allRows = futil.fileToVector("Transactions.dat");
   //current month
   Calendar cal = Calendar.getInstance();
   cal.setTime(new Date());
   int month = cal.get(Calendar.MONTH) + 1;
   String searchStr = department + "," + month + ",";
   int j = 1;
   for (int i = 0; i < allRows.size(); i++) {
     String str = (String) allRows.elementAt(i);
     if (str.indexOf(searchStr) > -1) {
       StringTokenizer st = new StringTokenizer(str, ",");
       st.nextToken();//bypass the department
       str = "   " + j + ". " + st.nextToken() + "/" + st.nextToken()
           + "~~~" + st.nextToken() + "Items" + "~~~"
           + st.nextToken() + " Dollars";
       j++;
       v.addElement(str);
     }
   }
   return v;
 }

}// end of class class ReportManager extends JFrame implements Observable {

 public static final String newline = "\n";
 public static final String SET_OK = "OK";
 public static final String EXIT = "Exit";
 private JPanel pSearchCriteria;
 private JComboBox cmbDepartmentList;
 private JButton btnOK, btnExit;
 private Vector observersList;
 private String department;
 public ReportManager() throws Exception {
   super("Observer Pattern - Example");
   observersList = new Vector();
   // Create controls
   cmbDepartmentList = new JComboBox();
   btnOK = new JButton(ReportManager.SET_OK);
   btnOK.setMnemonic(KeyEvent.VK_S);
   btnExit = new JButton(ReportManager.EXIT);
   btnExit.setMnemonic(KeyEvent.VK_X);
   pSearchCriteria = new JPanel();
   //Create Labels
   JLabel lblDepartmentList = new JLabel("Select a Department:");
   ButtonHandler vf = new ButtonHandler(this);
   btnOK.addActionListener(vf);
   btnExit.addActionListener(vf);
   JPanel buttonPanel = new JPanel();
   //----------------------------------------------
   GridBagLayout gridbag = new GridBagLayout();
   buttonPanel.setLayout(gridbag);
   GridBagConstraints gbc = new GridBagConstraints();
   buttonPanel.add(lblDepartmentList);
   buttonPanel.add(cmbDepartmentList);
   buttonPanel.add(btnOK);
   buttonPanel.add(btnExit);
   gbc.insets.top = 5;
   gbc.insets.bottom = 5;
   gbc.insets.left = 5;
   gbc.insets.right = 5;
   gbc.gridx = 0;
   gbc.gridy = 0;
   gridbag.setConstraints(lblDepartmentList, gbc);
   gbc.anchor = GridBagConstraints.WEST;
   gbc.gridx = 1;
   gbc.gridy = 0;
   gridbag.setConstraints(cmbDepartmentList, gbc);
   gbc.anchor = GridBagConstraints.EAST;
   gbc.insets.left = 2;
   gbc.insets.right = 2;
   gbc.insets.top = 40;
   gbc.gridx = 0;
   gbc.gridy = 6;
   gridbag.setConstraints(btnOK, gbc);
   gbc.anchor = GridBagConstraints.WEST;
   gbc.gridx = 1;
   gbc.gridy = 6;
   gridbag.setConstraints(btnExit, gbc);
   Container contentPane = getContentPane();
   contentPane.add(buttonPanel, BorderLayout.CENTER);
   try {
     UIManager.setLookAndFeel(new WindowsLookAndFeel());
     SwingUtilities.updateComponentTreeUI(ReportManager.this);
   } catch (Exception ex) {
     System.out.println(ex);
   }
   initialize();
   setSize(250, 200);
   setVisible(true);
 }
 private void initialize() throws Exception {
   // fill some test data here into the listbox.
   cmbDepartmentList.addItem("HardWare");
   cmbDepartmentList.addItem("Electronics");
   cmbDepartmentList.addItem("Furniture");
 }
 public void register(Observer obs) {
   // Add to the list of Observers
   observersList.addElement(obs);
 }
 public void unRegister(Observer obs) {
   // remove from the list of Observers
 }
 public void notifyObservers() {
   // Send notify to all Observers
   for (int i = 0; i < observersList.size(); i++) {
     Observer observer = (Observer) observersList.elementAt(i);
     observer.refreshData(this);
   }
 }
 public String getDepartment() {
   return department;
 }
 public void setDepartment(String dept) {
   department = dept;
 }
 class ButtonHandler implements ActionListener {
   ReportManager subject;
   public void actionPerformed(ActionEvent e) {
     if (e.getActionCommand().equals(ReportManager.EXIT)) {
       System.exit(1);
     }
     if (e.getActionCommand().equals(ReportManager.SET_OK)) {
       String dept = (String) cmbDepartmentList.getSelectedItem();
       //change in state
       subject.setDepartment(dept);
       subject.notifyObservers();
     }
   }
   public ButtonHandler() {
   }
   public ButtonHandler(ReportManager manager) {
     subject = manager;
   }
 }

}// end of class interface Observer {

 public void refreshData(Observable subject);

} interface Observable {

 public void notifyObservers();
 public void register(Observer obs);
 public void unRegister(Observer obs);

} class FileUtil {

 DataOutputStream dos;
 /*
  * Utility method to write a given text to a file
  */
 public boolean writeToFile(String fileName, String dataLine,
     boolean isAppendMode, boolean isNewLine) {
   if (isNewLine) {
     dataLine = "\n" + dataLine;
   }
   try {
     File outFile = new File(fileName);
     if (isAppendMode) {
       dos = new DataOutputStream(new FileOutputStream(fileName, true));
     } else {
       dos = new DataOutputStream(new FileOutputStream(outFile));
     }
     dos.writeBytes(dataLine);
     dos.close();
   } catch (FileNotFoundException ex) {
     return (false);
   } catch (IOException ex) {
     return (false);
   }
   return (true);
 }
 /*
  * Reads data from a given file
  */
 public String readFromFile(String fileName) {
   String DataLine = "";
   try {
     File inFile = new File(fileName);
     BufferedReader br = new BufferedReader(new InputStreamReader(
         new FileInputStream(inFile)));
     DataLine = br.readLine();
     br.close();
   } catch (FileNotFoundException ex) {
     return (null);
   } catch (IOException ex) {
     return (null);
   }
   return (DataLine);
 }
 public boolean isFileExists(String fileName) {
   File file = new File(fileName);
   return file.exists();
 }
 public boolean deleteFile(String fileName) {
   File file = new File(fileName);
   return file.delete();
 }
 /*
  * Reads data from a given file into a Vector
  */
 public Vector fileToVector(String fileName) {
   Vector v = new Vector();
   String inputLine;
   try {
     File inFile = new File(fileName);
     BufferedReader br = new BufferedReader(new InputStreamReader(
         new FileInputStream(inFile)));
     while ((inputLine = br.readLine()) != null) {
       v.addElement(inputLine.trim());
     }
     br.close();
   } // Try
   catch (FileNotFoundException ex) {
     //
   } catch (IOException ex) {
     //
   }
   return (v);
 }
 /*
  * Writes data from an input vector to a given file
  */
 public void vectorToFile(Vector v, String fileName) {
   for (int i = 0; i < v.size(); i++) {
     writeToFile(fileName, (String) v.elementAt(i), true, true);
   }
 }
 /*
  * Copies unique rows from a source file to a destination file
  */
 public void copyUniqueElements(String sourceFile, String resultFile) {
   Vector v = fileToVector(sourceFile);
   v = MiscUtil.removeDuplicates(v);
   vectorToFile(v, resultFile);
 }

} // end FileUtil class MiscUtil {

 public static boolean hasDuplicates(Vector v) {
   int i = 0;
   int j = 0;
   boolean duplicates = false;
   for (i = 0; i < v.size() - 1; i++) {
     for (j = (i + 1); j < v.size(); j++) {
       if (v.elementAt(i).toString().equalsIgnoreCase(
           v.elementAt(j).toString())) {
         duplicates = true;
       }
     }
   }
   return duplicates;
 }
 public static Vector removeDuplicates(Vector s) {
   int i = 0;
   int j = 0;
   boolean duplicates = false;
   Vector v = new Vector();
   for (i = 0; i < s.size(); i++) {
     duplicates = false;
     for (j = (i + 1); j < s.size(); j++) {
       if (s.elementAt(i).toString().equalsIgnoreCase(
           s.elementAt(j).toString())) {
         duplicates = true;
       }
     }
     if (duplicates == false) {
       v.addElement(s.elementAt(i).toString().trim());
     }
   }
   return v;
 }
 public static Vector removeDuplicateDomains(Vector s) {
   int i = 0;
   int j = 0;
   boolean duplicates = false;
   String str1 = "";
   String str2 = "";
   Vector v = new Vector();
   for (i = 0; i < s.size(); i++) {
     duplicates = false;
     for (j = (i + 1); j < s.size(); j++) {
       str1 = "";
       str2 = "";
       str1 = s.elementAt(i).toString().trim();
       str2 = s.elementAt(j).toString().trim();
       if (str1.indexOf("@") > -1) {
         str1 = str1.substring(str1.indexOf("@"));
       }
       if (str2.indexOf("@") > -1) {
         str2 = str2.substring(str2.indexOf("@"));
       }
       if (str1.equalsIgnoreCase(str2)) {
         duplicates = true;
       }
     }
     if (duplicates == false) {
       v.addElement(s.elementAt(i).toString().trim());
     }
   }
   return v;
 }
 public static boolean areVectorsEqual(Vector a, Vector b) {
   if (a.size() != b.size()) {
     return false;
   }
   int i = 0;
   int vectorSize = a.size();
   boolean identical = true;
   for (i = 0; i < vectorSize; i++) {
     if (!(a.elementAt(i).toString().equalsIgnoreCase(b.elementAt(i)
         .toString()))) {
       identical = false;
     }
   }
   return identical;
 }
 public static Vector removeDuplicates(Vector a, Vector b) {
   int i = 0;
   int j = 0;
   boolean present = true;
   Vector v = new Vector();
   for (i = 0; i < a.size(); i++) {
     present = false;
     for (j = 0; j < b.size(); j++) {
       if (a.elementAt(i).toString().equalsIgnoreCase(
           b.elementAt(j).toString())) {
         present = true;
       }
     }
     if (!(present)) {
       v.addElement(a.elementAt(i));
     }
   }
   return v;
 }

}// end of class

//File: Transactions.dat /* Furniture,1,1,2,200 Furniture,1,10,2,400 Furniture,1,15,2,400 Furniture,2,1,2,2000 Furniture,2,10,2,2000 Furniture,2,15,2,1000 Furniture,3,1,2,2000 Furniture,3,10,2,1000 Furniture,3,15,2,1000 Furniture,4,1,2,200 Furniture,4,10,2,400 Furniture,4,15,2,400 Furniture,5,1,2,2000 Furniture,5,1,2,2000 Furniture,5,1,2,2000 Furniture,6,10,2,2000 Furniture,6,15,2,2000 Furniture,6,1,2,1000 Furniture,7,10,2,200 Furniture,7,15,2,700 Furniture,7,1,2,100 Furniture,8,10,2,200 Furniture,8,15,2,200 Furniture,8,1,2,1600 Furniture,9,10,2,200 Furniture,9,15,2,200 Furniture,9,1,2,600 Furniture,10,10,2,1000 Furniture,10,15,2,2000 Furniture,10,1,2,1000 Furniture,11,10,2,200 Furniture,11,15,2,200 Furniture,11,1,2,800 Furniture,12,10,2,2000 Furniture,12,15,2,2000 Furniture,12,1,2,2000 HardWare,1,1,2,2000 HardWare,1,10,2,2000 HardWare,1,15,2,1000 HardWare,2,1,2,2000 HardWare,2,10,2,2000 HardWare,2,15,2,2000 HardWare,3,1,2,200 HardWare,3,10,2,1000 HardWare,3,15,2,800 HardWare,4,1,2,200 HardWare,4,10,2,400 HardWare,4,15,2,400 HardWare,5,1,2,200 HardWare,5,1,2,200 HardWare,5,1,2,600 HardWare,6,10,2,2000 HardWare,6,15,2,2000 HardWare,6,1,2,1000 HardWare,7,10,2,200 HardWare,7,15,2,700 HardWare,7,1,2,100 HardWare,8,10,2,200 HardWare,8,15,2,200 HardWare,8,1,2,600 HardWare,9,10,2,200 HardWare,9,15,2,200 HardWare,9,1,2,600 HardWare,10,10,2,2000 HardWare,10,15,2,2000 HardWare,10,1,2,2000 HardWare,11,10,2,1000 HardWare,11,15,2,200 HardWare,11,1,2,1800 HardWare,12,10,2,200 HardWare,12,15,2,200 HardWare,12,1,2,600 Electronics,1,1,2,200 Electronics,1,10,2,400 Electronics,1,15,2,400 Electronics,2,1,2,2000 Electronics,2,10,2,2000 Electronics,2,15,2,1000 Electronics,3,1,2,2000 Electronics,3,10,2,1000 Electronics,3,15,2,1000 Electronics,4,1,2,200 Electronics,4,10,2,400 Electronics,4,15,2,400 Electronics,5,1,2,200 Electronics,5,1,2,200 Electronics,5,1,2,600 Electronics,6,10,2,2000 Electronics,6,15,2,2000 Electronics,6,1,2,1000 Electronics,7,10,2,200 Electronics,7,15,2,700 Electronics,7,1,2,100 Electronics,8,10,2,1200 Electronics,8,15,2,1200 Electronics,8,1,2,1600 Electronics,9,10,2,200 Electronics,9,15,2,200 Electronics,9,1,2,600 Electronics,10,10,2,1000 Electronics,10,15,2,2000 Electronics,10,1,2,1000 Electronics,11,10,2,1000 Electronics,11,15,2,200 Electronics,11,1,2,1800 Electronics,12,10,2,200 Electronics,12,15,2,200 Electronics,12,1,2,600

  • /


 </source>
   
  
 
  



Observer Pattern in Java 2

   <source lang="java">
 

//[C] 2002 Sun Microsystems, Inc.--- import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Iterator; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class RunObserverPattern {

 public static void main(String[] arguments) {
   System.out.println("Example for the Observer pattern");
   System.out.println("This demonstration uses a central observable");
   System.out.println(" object to send change notifications to several");
   System.out.println(" JPanels in a GUI. Each JPanel is an Observer,");
   System.out.println(" receiving notifcations when there has been some");
   System.out.println(" change in the shared Task that is being edited.");
   System.out.println();
   System.out.println("Creating the ObserverGui");
   ObserverGui application = new ObserverGui();
   application.createGui();
 }

} class Task {

 private String name = "";
 private String notes = "";
 private double timeRequired;
 public Task() {
 }
 public Task(String newName, String newNotes, double newTimeRequired) {
   name = newName;
   notes = newNotes;
   timeRequired = newTimeRequired;
 }
 public String getName() {
   return name;
 }
 public String getNotes() {
   return notes;
 }
 public double getTimeRequired() {
   return timeRequired;
 }
 public void setName(String newName) {
   name = newName;
 }
 public void setTimeRequired(double newTimeRequired) {
   timeRequired = newTimeRequired;
 }
 public void setNotes(String newNotes) {
   notes = newNotes;
 }
 public String toString() {
   return name + " " + notes;
 }

} class TaskChangeObservable {

 private ArrayList observers = new ArrayList();
 public void addTaskChangeObserver(TaskChangeObserver observer) {
   if (!observers.contains(observer)) {
     observers.add(observer);
   }
 }
 public void removeTaskChangeObserver(TaskChangeObserver observer) {
   observers.remove(observer);
 }
 public void selectTask(Task task) {
   Iterator elements = observers.iterator();
   while (elements.hasNext()) {
     ((TaskChangeObserver) elements.next()).taskSelected(task);
   }
 }
 public void addTask(Task task) {
   Iterator elements = observers.iterator();
   while (elements.hasNext()) {
     ((TaskChangeObserver) elements.next()).taskAdded(task);
   }
 }
 public void updateTask(Task task) {
   Iterator elements = observers.iterator();
   while (elements.hasNext()) {
     ((TaskChangeObserver) elements.next()).taskChanged(task);
   }
 }

} interface TaskChangeObserver {

 public void taskAdded(Task task);
 public void taskChanged(Task task);
 public void taskSelected(Task task);

} class TaskEditorPanel extends JPanel implements ActionListener,

   TaskChangeObserver {
 private JPanel controlPanel, editPanel;
 private JButton add, update, exit;
 private JTextField taskName, taskNotes, taskTime;
 private TaskChangeObservable notifier;
 private Task editTask;
 public TaskEditorPanel(TaskChangeObservable newNotifier) {
   notifier = newNotifier;
   createGui();
 }
 public void createGui() {
   setLayout(new BorderLayout());
   editPanel = new JPanel();
   editPanel.setLayout(new GridLayout(3, 2));
   taskName = new JTextField(20);
   taskNotes = new JTextField(20);
   taskTime = new JTextField(20);
   editPanel.add(new JLabel("Task Name"));
   editPanel.add(taskName);
   editPanel.add(new JLabel("Task Notes"));
   editPanel.add(taskNotes);
   editPanel.add(new JLabel("Time Required"));
   editPanel.add(taskTime);
   controlPanel = new JPanel();
   add = new JButton("Add Task");
   update = new JButton("Update Task");
   exit = new JButton("Exit");
   controlPanel.add(add);
   controlPanel.add(update);
   controlPanel.add(exit);
   add.addActionListener(this);
   update.addActionListener(this);
   exit.addActionListener(this);
   add(controlPanel, BorderLayout.SOUTH);
   add(editPanel, BorderLayout.CENTER);
 }
 public void setTaskChangeObservable(TaskChangeObservable newNotifier) {
   notifier = newNotifier;
 }
 public void actionPerformed(ActionEvent event) {
   Object source = event.getSource();
   if (source == add) {
     double timeRequired = 0.0;
     try {
       timeRequired = Double.parseDouble(taskTime.getText());
     } catch (NumberFormatException exc) {
     }
     notifier.addTask(new Task(taskName.getText(), taskNotes.getText(),
         timeRequired));
   } else if (source == update) {
     editTask.setName(taskName.getText());
     editTask.setNotes(taskNotes.getText());
     try {
       editTask
           .setTimeRequired(Double.parseDouble(taskTime.getText()));
     } catch (NumberFormatException exc) {
     }
     notifier.updateTask(editTask);
   } else if (source == exit) {
     System.exit(0);
   }
 }
 public void taskAdded(Task task) {
 }
 public void taskChanged(Task task) {
 }
 public void taskSelected(Task task) {
   editTask = task;
   taskName.setText(task.getName());
   taskNotes.setText(task.getNotes());
   taskTime.setText("" + task.getTimeRequired());
 }

} class TaskHistoryPanel extends JPanel implements TaskChangeObserver {

 private JTextArea displayRegion;
 public TaskHistoryPanel() {
   createGui();
 }
 public void createGui() {
   setLayout(new BorderLayout());
   displayRegion = new JTextArea(10, 40);
   displayRegion.setEditable(false);
   add(new JScrollPane(displayRegion));
 }
 public void taskAdded(Task task) {
   displayRegion.append("Created task " + task + "\n");
 }
 public void taskChanged(Task task) {
   displayRegion.append("Updated task " + task + "\n");
 }
 public void taskSelected(Task task) {
   displayRegion.append("Selected task " + task + "\n");
 }

} class TaskSelectorPanel extends JPanel implements ActionListener,

   TaskChangeObserver {
 private JComboBox selector = new JComboBox();
 private TaskChangeObservable notifier;
 public TaskSelectorPanel(TaskChangeObservable newNotifier) {
   notifier = newNotifier;
   createGui();
 }
 public void createGui() {
   selector = new JComboBox();
   selector.addActionListener(this);
   add(selector);
 }
 public void actionPerformed(ActionEvent evt) {
   notifier.selectTask((Task) selector.getSelectedItem());
 }
 public void setTaskChangeObservable(TaskChangeObservable newNotifier) {
   notifier = newNotifier;
 }
 public void taskAdded(Task task) {
   selector.addItem(task);
 }
 public void taskChanged(Task task) {
 }
 public void taskSelected(Task task) {
 }

} class ObserverGui {

 public void createGui() {
   JFrame mainFrame = new JFrame("Observer Pattern Example");
   Container content = mainFrame.getContentPane();
   content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
   TaskChangeObservable observable = new TaskChangeObservable();
   TaskSelectorPanel select = new TaskSelectorPanel(observable);
   TaskHistoryPanel history = new TaskHistoryPanel();
   TaskEditorPanel edit = new TaskEditorPanel(observable);
   observable.addTaskChangeObserver(select);
   observable.addTaskChangeObserver(history);
   observable.addTaskChangeObserver(edit);
   observable.addTask(new Task());
   content.add(select);
   content.add(history);
   content.add(edit);
   mainFrame.addWindowListener(new WindowCloseManager());
   mainFrame.pack();
   mainFrame.setVisible(true);
 }
 private class WindowCloseManager extends WindowAdapter {
   public void windowClosing(WindowEvent evt) {
     System.exit(0);
   }
 }

}



 </source>
   
  
 
  



Using Observer pattern with two observers observing a changing integer

   <source lang="java">

import java.util.Observable; import java.util.Observer; public class Main {

 public static void main(String[] args) {
   MyObservable observable = new MyObservable();
   MyObserver1 observer1 = new MyObserver1();
   MyObserver2 observer2 = new MyObserver2();
   observable.addObserver(observer1);
   observable.addObserver(observer2);
   observable.start();
   try {
     Thread.sleep(20000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }

} class MyObserver1 implements Observer {

 public void update(Observable o, Object arg) {
   Integer count = (Integer) arg;
 }

} class MyObserver2 implements Observer {

 public void update(Observable o, Object arg) {
   Integer count = (Integer) arg;
 }

} class MyObservable extends Observable implements Runnable {

 public MyObservable() {
 }
 public void start() {
   new Thread(this).start();
 }
 public void run() {
   int count = 0;
   try {
     Thread.sleep(3000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   count++;
   setChanged();
   notifyObservers(new Integer(count));
 }

}

 </source>