Pregunta

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

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top