应用程序架构:在java中保持串行连接打开
我正在开发一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的经验是静态构造函数可能很混乱。另外,如果您想通过编写单元测试来模拟串行通信来测试逻辑,这种架构会变得很困难。
另一种方法是使用带有构造函数的 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:
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.