views:

331

answers:

5

Hi,

I'm writing an application which will run as a daemon. UIs will connect to it over TCP. Now, there is a class called UiTcpInterface which will handle all communication between the UI and this daemon.

Now, I'm faced with the problem of ensuring there is only one instance of UiTcpInterface. What would be the best way to do it? Currently, I've thought of two ways:

  1. This is the classic singleton pattern: make the constructor private, and provide a static instance() method to the class UiTcpInterface
  2. Implement all functionality as static members of UiTcpInterface. The main method will make sure that all initialization is done.

Which of these two should I follow? Can you please give me a pro-con list of the two methods?

Thanks :)

A: 

I'd choose the first way to implement it because it will be so much easier to change to non singleton if you change your mind later.

leiz
A: 

SingleTon is better,
You can always reset the object status, serialize the object (not sure if this works in c++). Alot of other benefits comes with singleton against a static class. I'd prefer using a static class methods to wrap a general functions (like Math Class)

Omar Dolaimy
A: 

Actually, none of the two is primary about single instance, but of global access. If you want single instance, make sure the code that manages the modules needing it will create only a single instance and pass it down.
If you want code to enforce it I would suggest an instance counter and an assert in the constructor that checks that it is the only instance.

+1  A: 

I would prefer the singleton pattern. One argument is testability. For unit tests it's easier e.g. to return a mock object from instance(). Also, if you have e.g. different implementations or no longer a single object the changes are easier.

ur
Hmm.. i like the testability point of view
Here Be Wolves