Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c++ - Static members class vs. normal c-like interface

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. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your proposal with namespaces has a slight weakness in maintainability - if you need to change the interface for some reason, you have to remember to change both the interface (.h) and implementation (.cpp), or a mismatch may not be detected until link time. If you use a class, then the compiler can detect an error such as a number of parameters mismatch.

On the other hand, since the implementation (service_) in your case only appears in the .cpp file, you may be able to change the private implementation of the locator without forcing a recompile of code that depends on the locator. (Common class-based patterns can provide this same encapsulation.)

These are fairly minor differences. A public namespace containing functions is almost exactly the same as a class with only static member functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...