gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:58:34 24 4
gpt4 key购买 nike

我编写了一个电子邮件接收逻辑(类名: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();

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

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

}

还请解释一下为什么有 2 个变量 Observable o 和 Object arg?

最佳答案

您必须调用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
}

关于java - Observer - 围绕电子邮件接收逻辑的可观察模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53614848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com