Singleton and Interface implementation

前端 未结 1 805
梦毁少年i
梦毁少年i 2020-12-12 01:24

I have an interface class Interface with pure virtual methods.

class Interface
{
public:
    virtual void DoSomething() = 0;
}

相关标签:
1条回答
  • 2020-12-12 01:54

    "1) Should I invoke Interface or Implementation class from the rest of my program whenever I need to use the class? How exactly should I do so?"

    Use the interface, that will less clutter your code with Implementation::Instance() calls:

     Interface& module = Implementation::Instance();
           // ^ 
    

    Note the reference, assignment and copy won't work.

    "2) How should the method Instance() look like?"

    The common consensus is to use Scott Meyer's approach:

     Implementation& Instance() {
         static Implementation theInstance;
         return theInstance;
     }
    

    The better alternative is not to use a singleton at all but make your code ready to operate on the Interface exclusively:

     class Interface {
          // ...
     };
    
     class Impl : public Interface {
          // ...
     };
    
     class Client {
         Interface& if_;
     public:
         Client(Interface& if__) : if_(if__) {}
          // ...
     }
    
     int main() {
         Impl impl;
         Client client(impl);
     };
    
    0 讨论(0)
提交回复
热议问题