Hey there.
After reading here about the Service Locator pattern, it got me thinking wether a class with only static members really is the way to go, or if a normal c-like interace wouldn't be more appropriate. I see people throwing around the class
keyword all the time when they don't even need it.
Example with static members class taken from the linked page:
class Locator
{
public:
static IAudio* GetAudio() { return service_; }
static void Register(IAudio* service)
{
service_ = service;
}
private:
static IAudio* service_;
};
Here's a way one could do it too:
// in .h
namespace Locator{
IAudio* GetAudio();
void Register(IAudio* service);
}
// in .cpp
namespace Locator{
namespace {
IAudio* service_;
}
IAudio* GetAudio() {
return service_;
}
void Register(IAudio* service) {
service_ = service;
}
}
Both examples can be called exactly the same way with Locator::GetAudio()
and Locator::Register(...)
.
Is one of the above superior to the other? Are they the same? Are there maybe better ways to accomplish this? Or is it just about personal preferences? Thanks for any help. :)