// Project: Observer // Module: messageboard2 Example // Source code file: Main.java // Illustrate the Observer software pattern. // In addition to the currentMessage, an // archive of old messages is kept in // an array list. public class Main { public static void main(String[] args) throws InterruptedException { // Test the Observer and Observable classes. MessageBoard board = new MessageBoard( ); Student bob = new Student("Bob"); Student alice = new Student("Alice"); board.addObserver(bob); board.addObserver(alice); System.out.println("Number of observers: " + board.countObservers( )); System.out.println( ); board.changeMessage("Homework 5 Description posted"); // Sleep (pause) for 1000 milliseconds (1 second). Thread.sleep(1000); board.changeMessage("Final Exam Review posted"); Thread.sleep(1000); board.changeMessage("Grades for Homework 5 posted"); Thread.sleep(1000); // Anyone allowed to check the message archive even // if he or she has not been recently been notified. // board.hasChanged will be true if the messages are in // the process of being changed before the observers are // notified. If board.hasChanged is false, a student is // guaranteed to obtain the most recently posted messages. if (!board.hasChanged( )) { System.out.println("Message Archive"); System.out.println("===================="); System.out.println(board.getArchive( )); } } }