3

I am re-factoring some code and an having an issue with retrieving data from two parallel processes.

I have an application that sends packets back and forth via different mediums (ex: RS232, TCP/IP, etc). The jist if of this question is that there are two parallel processes going on.

I hope the picture below displays what is going on better than I can word it:enter image description here

SetupRS232() class creates a new instance of the SerialPort by:

SerialPort serialPort = new SerialPort();

My question is, what is the best way that the Communicator() class, which sends out the packet via the respective medium, get access to the SerialPort object from the SetupRS232 class? I can do it with a Singleton but have heard that they are generally not the best design to go by.

I am trying to follow SRP but I do feel like I am doing something wrong here. Communicator() will need to go out of it's way to get access to SetupRS232() to get access to the SerialPort class. I actually haven't found a way to even get access to it.

Would designing each medium class, for example, SetupRS232(), SetupTCPIP, as a singleton be the best way to approach this problem?

2 Answers 2

3

I think the pattern you are looking for is an Adapter

You can implement an ICommunicator interface to effect an Adapter pattern so that your Communicator process does not need to know what kind of transport mechanism it is using

creating the ports and sockets et al would be the responsibility of a configuration object/process, not the Communicator

that is, if i understood your question correctly!

1
  • Thanks Steve A. Lowe. After reading the article, I think this is the best way to go and will fit my design. Thanks again!
    – brazc0re
    Jun 7, 2012 at 16:02
0

The difference between a singleton and an object that's only created once is that a singleton enforces it. In your case, I don't think you really need to enforce it. All you really need is a place for your setup classes to register the SerialPort instances, and a way for your Communicator to access that registry. This way the setup classes and the Communicator are safely decoupled from each other. Then you'll just have to be careful that the "registry" is thread-safe and that interaction with it is well-defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.