观察者-围绕电子邮件接收逻辑的可观察模型

时间:2018-12-04 14:12:49

标签: java observable observer-pattern observers

我写了一封电子邮件接收逻辑(类名:Mail_Receive_Logic)。此类将我所有未读的电子邮件下载到messages数组中。

我也有EmailStatPrinterEmailStatRecorder类。 EmailStatPrinter有一个writeToConsole方法,该方法将数组打印到屏幕上。 EmailStatRecorder有一个writeToFile方法,该方法将数组写入文本文件。

我想以观察者可观察的方式实现这种逻辑。

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

我的主要方法如下

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();

我应该如何编写每个观察者类的 update方法,以便他们接收消息数组并将其打印在控制台和文本文件上。即我想知道在每个观察者类的以下代码段中写什么。

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

    }

也请向我解释一下,为什么有两个变量Observable o和Object arg?

1 个答案:

答案 0 :(得分:2)

您必须致电Observable.notifyObservers()并提供arg。可以是任何您喜欢的东西。对于您的情况,我认为您会想要类似的东西:

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

然后在您的观察者中,您将收到以下消息:

@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
}