Application architecture: saving serial connections in java

I am working on a Java project that interacts with two serial port devices using the Suns serial port library. I have to somehow keep in touch with devices open all the time and handle events from them (with verified data ...). The application interacts with the user (through SOAP) and is a console application (later it can be transferred to the application server, but at the moment it is ignored).

The question is how to handle devices. At the moment, I have a static class with two static variables that return objects that the device processes. In the static constructor of this class, I open the connections and set the initial parameters, etc. Then, when I need a device in the application, I get it somehow like Device.MyDevice, Device. MyDevice2 etc .... Is there a better way to do this or is this normal?

Remember that I have no problems connecting to devices, I need architectural tips.

thanks

+4
source share
1 answer

My experience is that static constructors can be messy. In addition, if you want to test logic by writing unit tests to mock serial communications, this architecture will make it harder.

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 two real devices that you would communicate with as public static end fields of the class. Something like that:

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 may have a device interface that is implemented by this device class - this helps to make the development cycle more rigorous if you can test the logic of interaction with devices without having to deal with the device itself.

+3
source

Source: https://habr.com/ru/post/1339740/


All Articles