How do I implement a "single instance"-like design?


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 :)

9/9/2009 8:31:47 AM

Accepted Answer

5/23/2017 10:32:55 AM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow