应用程序架构:在java中保持串行连接打开

发布于 2024-10-17 09:20:30 字数 367 浏览 5 评论 0原文

我正在开发一个 Java 项目,该项目使用 Suns 的串行端口库与两个串行端口设备进行通信。我必须以某种方式保持与设备的连接始终打开并处理它们的事件(在数据恢复时......)。该应用程序正在与用户交互(通过 SOAP),并且是一个控制台应用程序(稍后它可能会移动到应用程序服务器,但现在忽略它)。

问题是如何处理设备。现在我有一个带有两个静态变量的静态类,它们返回处理设备的对象。在该类的静态构造函数中,我打开连接并设置初始参数等。然后,每当我在应用程序中需要设备时,我都会通过以下方式获取它:Device.MyDevice, Device.我的设备2等... 有没有更好的方法可以做到这一点,或者这个可以吗?

请记住,我在连接设备方面没有问题,我需要架构建议。

谢谢

I'm working on a project in Java, which is communicating with two serial port devices using Suns's serial port library. I must somehow keep connections to devices open all the time and handle events of them (on data revieved...). The application is interacting with user (via SOAP) and is a console application (later it might be moved to an application server, but ignore that for now).

The question is how to handle devices. For now I have a static class with two static variables that returns objects that handle the device. In that class's static constructor I open connections and set initial parameters etc. Then whenever I need a device in application, I get it by something like: Device.MyDevice, Device. MyDevice2 etc...
Is there any better way of doing this or is this one ok?

Remember, I don't have problems with connecting to devices, I need architectural advice.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

翻了热茶 2024-10-24 09:20:30

我的经验是静态构造函数可能很混乱。另外,如果您想通过编写单元测试来模拟串行通信来测试逻辑,这种架构会变得很困难。

另一种方法是使用带有构造函数的 Device 类,该构造函数接受一些配置参数(例如要使用哪个串行端口),并将要连接的两个实际设备作为该类的公共静态最终字段。像这样的事情:

public class Device {
    public static final Device Device1 = new Device(...);
    public static final Device Device2 = new Device(...);

    public Device( ... ) {

    }
}

为了使测试更加容易,您可以拥有该设备类实现的设备接口 - 如果您可以测试与设备交互的逻辑而不处理设备本身,它有助于使开发循环更紧密。

My experience has been that static constructors can be messy. Also, if you wanted to test the logic by writing unit tests to mock the serial communication, this architecture would make it hard.

An alternative would be to have a Device class with a constructor that takes some configuration arguments (which serial port to use, for example), and have the two actual devices you would connect with as public static final fields of the class. Something like this:

public class Device {
    public static final Device Device1 = new Device(...);
    public static final Device Device2 = new Device(...);

    public Device( ... ) {

    }
}

To make tests even easier, you could have a Device interface that this device class implements - it helps make the development loop tighter if you can test the logic for interacting with devices without dealing with the device itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文