Singleton and Interface implementation

半城伤御伤魂 提交于 2019-12-17 21:32:47

问题


I have an interface class Interface with pure virtual methods.

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

Also, there is a class Implementation that implements the interface.

class Implementation : public Interface
{
    void DoSomething();
}

In my program I need to have a Singleton (single instance) of Implementation/Interface pair. There are many pairs of Implementation/Interface classes in the program, but very few Implementation classes for one Interface class.

QUESTIONS:

  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?

     //Interface needs to know about Implementation
     Interface * module = Interface::Instance();
    
     //No enforcement of Interface
     Implementation * module = Implementation::Instance();
    
     //A programmer needs to remember Implementation and Interface names
     Interface * module = Implementation::Instance();
    
     //May be there is some better way
    
  2. How should the method Instance() look like?


回答1:


"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);
 };


来源:https://stackoverflow.com/questions/30557133/singleton-and-interface-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!