Reputation: 26583
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
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 :)
Upvotes: 0
Views: 6187
Reputation: 2947
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.
Upvotes: 1
Reputation: 6295
This has been discussed many, many times.
Singleton - Why use classes?
Problems with Singleton Pattern
Why choose a static class over a singleton implementation?
https://stackoverflow.com/questions/1304647/static-storage-vs-singleton-why-people-prefer-singleton-closed
Upvotes: 4
Reputation: 796
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.
Upvotes: 1
Reputation: 5160
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)
Upvotes: 0
Reputation: 4052
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.
Upvotes: 0