1
votes

I have an email receiving logic written (class name: Mail_Receive_Logic). This class downloads all my unread emails into a messages array.

I also have classes EmailStatPrinter and EmailStatRecorder classes. EmailStatPrinter has a writeToConsole method which prints the array onto screen. EmailStatRecorder has a writeToFile method which writes the array in a text file.

I want to implement this logic in an observer-observable manner.

public class Mail_Receive_Logic extends Observable{ 
public class EmailStatPrinter implements Observer{
public class EmailStatRecorder implements Observer{

My main method looks like this

public static void main(String[] args) throws ClassNotFoundException {

    // observable
    Mail_Receive_Logic receiveMail = new Mail_Receive_Logic(usernameReceiving, passwordReceiving, fileReceivePath);

    // observer
    EmailStatPrinter writeToConsole = new EmailStatPrinter();
    EmailStatRecorder writeToFile = new EmailStatRecorder();

    receiveMail.addObserver(writeToConsole);
    receiveMail.addObserver(writeToFile);

    Thread receive = new Thread (new Runnable() {
        public void run() { 
            try {
                while (true) {
                    receiveMail.receive();  
                }
            } catch (InterruptedException e) {}
        }
    }); 

    receive.start();

How should I write the update method of each observer classes such that they take in messages array and print it on console and text file. i.e I want to know what to write in following code segment for each observer classes.

@Override
    public void update(Observable o, Object arg) {
        // TODO Auto-generated method stub

    }

Please also explain me that why is there 2 variables Observable o and Object arg?

1

1 Answers

2
votes

You have to call Observable.notifyObservers() and supply the arg. It can be anything you like. In your case I think you would want something like:

try {
    while (true) {
        receiveMail.receive();
        receiveMail.notifyObservers(messages);
    }
}
catch (InterruptedException e) {
}

Then in your Observers you would receive the messages as:

@Override
public void update(Observable o, Object arg) {
    // The first arg is the thing you were observing (receiveMail in this case)
    // The second arg is the messages that was passed by the receiveMail instance
}