The problem is mostly OOP design problem.
I have a class which handles the connection and communication with hardware (Let’s say via USB) – CommClass. It has few methods – connect(), disconnect(), read(), write().
The application itself has few other classes that want to communicate with the same HW trough CommClass.
The question – how you usually do that?
I have few ideas in mind:
- In the parent class or in main create instance of
CommClass, callconnect()and pas a pointer to all the classes (constructors). At the end –disconnect(). - Each method from each class will create an
CommClassobject in the stack when it needs it. – here the problem is that it has to callconnect()method in order to request a handle to the USB and so on every time… - Use static methods from
CommClass…
If you expect to have a single connection to the device (let’s say a USB device) then it makes sense to have one single instance of your
CommClassorICommClassif you want to have a more elegant design and work with an Interface that is implemented by yourCommClass. You can also wrap the connection (class or interface) into a singleton, that way you can make sure that the connection is made and disposed only once. This works best if you expect to use a single connection at a time in a single threaded application. In a multi threaded or multi connection environment you could try using a object pool design pattern.