Reputation: 9
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.
Upvotes: 0
Views: 392
Reputation: 238401
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
}
Upvotes: 3