gpt4 book ai didi

Java 通知设计模式

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

我有一个基于网络的应用程序,每次在后端执行某些操作时,它都会从服务器向客户端发送消息。现在,我正在编写一些测试来查看发送到客户端的消息是否是预期的消息。每个操作在执行时都会生成一条发送到客户端的特定消息。在我的测试中,我创建了一个 WebSocket 客户端来监听服务器。现在,当我执行某个操作时,我应该检查是否正在发送该操作的预期消息。请注意,服务器需要一些时间来发送消息。

以下只是伪代码:

class ApplicationTest
public void checkIfEventCreatedMsgIsSent() {
Application.createNewEvent("Id101");
// Wait till the application sends message to the client
// And then check that the message sent is the correct one
// if (expectedMessage == recievedMessageFromClient) {
// success();
// }

}

class Client
public void readMessage(Message message) {
// Received the new event message with Id101
// Now this message should be sent to ApplicationTest.checkIfEventCreatedMsgIsSent and confirmed by it
}
}

我收到消息给客户,一切都很好。

但我无法弄清楚如何通知 ApplicationTest 客户端已收到消息,然后进行验证。我尝试在这里实现观察者设计模式,但这只会让人更加困惑。我应该如何实现这个以及哪种设计模式最适合这种场景?

最佳答案

用一些基本假设重写你的类

我们正在存储一个值的映射,例如 Map<String, Object> msg = new HashMap<String, Object>()它将加载 (EventId, EventDetailsObject).上面的 Map msg 将存储在 ServletContext 中,它也可以是 MQ 上的持久消息或 db 中的值。客户端不发送任何确认,但 ApplicationTest 会轮询以查找事件是否已创建尽量不深入了解其他实现细节,请告诉我这对您是否有意义?

class ApplicationTest
public void checkIfEventCreatedMsgIsSent() {
Application.createNewEvent("Id101");
// Wait till the application sends message to the client
// And then check that the message sent is the correct one
// if (expectedMessage == recievedMessageFromClient) {
// success();
// }
int iCount = 0;
int final MAXCOUNT = 5;
// Assuming client doesnt send an acknowledgement
// but Server pools to find that
// Below is Polling code method to check if event is created
// Servlet context is an example
// it could be a persistent message on MQ or a value in db
while(iCount < 5) {
if (servletcontext.get(msg).get("Id101") == null) {
count++;
sleep(5000);
} else { System.out.println("Eureka, msg is sent!")}
}
}
class Client{
public void readMessage(Message message) {
// Received the new event message with Id101
// Now this message should be sent to
// ApplicationTest.checkIfEventCreatedMsgIsSent and confirmed by it
// Below msg is a singleton object in Servlet context as an example
// it could be a persistent message on MQ or a value in db
// Map<String, Object> msg = new HashMap<String, Object>();
synchronized(servletContext) {
servletcontext.get(msg).put("Id101", <object>);
}
}
}

关于Java 通知设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22540204/

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