0

I am developing a class to control a network adapter and I need to ensure that there's only a single instance of this class. Global access isn't necessary as this class is only used by clients that perform network operations, so I think that's not the case for the singleton pattern.

Currently I have a factory which has a static instance of this netAdapter but I'm not sure that's a good solution.

What's the best way to do this and avoid testability problems?

EDIT: I have more than one adapter(wifi, ethernet, 2G/3G/4G), but I can only have a single instance of each.

balgajo
  • 9
  • 2
  • 5
    XY problem? Why do you care how many instances of class are there? – SergeyA Feb 09 '17 at 16:10
  • 1
    [Singletons](https://en.wikipedia.org/wiki/Singleton_pattern) are nice for this. – Izuka Feb 09 '17 at 16:11
  • 3
    @Isuka, singletons are good for nothing. – SergeyA Feb 09 '17 at 16:13
  • 2
    @SergeyA Could you elaborate on that point? That could be interesting for the question too. Definitely not saying that a singleton is the best solution out there, but it does accomplish the work, no? – Izuka Feb 09 '17 at 16:16
  • 3
    @Isuka, nothing to elaborate. There is no need to use singleton whatsoever. Never. – SergeyA Feb 09 '17 at 16:18
  • @Isuka [here, have a post](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) – jaggedSpire Feb 09 '17 at 16:20
  • Singleton is the common pattern where you need exactly one instance. Your "factory which has a static instance" is a singleton. That's called Meyers' singleton. Alternatively you can invert things and just pass an instance of the class in question, down as an argument. To everything. – Cheers and hth. - Alf Feb 09 '17 at 16:22
  • @jaggedSpire Thanks for that, even though I was more asking for precisions so that the QA himself can see what are the pros/cons there. – Izuka Feb 09 '17 at 16:23

1 Answers1

3

I need to ensure that there's only a single instance of this class.

... so I think that's not the case for the singleton pattern.

Limiting a class to a single instance is the very definition of singleton pattern.

What's the best way to do this and avoid testability problems?

I don't think testability problems can be avoided if you limit class to a single instance. Best approach might be to forget about such requirement.

Global access isn't necessary

Then I suggest a local static variable:

void function_that_needs_a_single_instance_ever() {
    static singleton_class instance;
    // do something with your singleton
}
Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • The static local suffers a number of problems, too. In Microsoft environments, they cannot be initialized safely in a threaded environment, even with C++11. We've got two bug reports open because of Microsoft games. – jww Feb 10 '17 at 04:09
  • @jww thanks for the heads up. I wasn't aware of that particular lack of standards conformance. – eerorika Feb 10 '17 at 21:38