c++ 单例和接口实现

我有一个接口类接口与纯虚方法.

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

此外,还有一个实现接口的类实现.

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

在我的程序中,我需要一个Singleton(单实例)的Implementation / Interface对.程序中有许多实现/接口类对,但是一个接口类的实现类很少.

问题:

>每当我需要使用该类时,我应该从我的程序的其余部分调用Interface或Implementation类吗?
我该怎么办呢?

 //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

> Instance()方法应该如何?

“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?”

使用接口,通过Implementation :: Instance()调用可以减少代码的混乱:

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

请注意,引用,分配和复制将不起作用.

“2) How should the method Instance() look like?”

共同的共识是使用Scott Meyer’s approach

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

更好的选择是根本不使用单例,而是让代码准备好在接口上独占操作:

 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

转载注明原文:c++ 单例和接口实现