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:
instance()method to the class
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?
This has been discussed many, many times.
Singleton - Why use classes?
Problems with Singleton Pattern
Why choose a static class over a singleton implementation?
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.