Observer Pattern - Example in 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
*/
Related examples in the same category