c++ - 单例和接口(interface)实现

标签 c++ interface singleton

我有一个带有纯虚方法的接口(interface)类Interface

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

此外,还有一个实现该接口(interface)的类Implementation

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

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

问题:

  1. 每当我需要使用类时,是否应该从程序的其余部分调用InterfaceImplementation 类? 我具体应该怎样做呢?

     //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. 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?"

使用接口(interface),通过 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;
 }

更好的选择是根本不使用单例,而是让您的代码准备好专门在Interface上操作:

 class Interface {
      // ...
 };

 class Impl : public Interface {
      // ...
 };

 class Client {
     Interface& if_;
 public:
     Client(Interface& if__) : if_(if__) {}
      // ...
 }

 int main() {
     Impl impl;
     Client client(impl);
 };

关于c++ - 单例和接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557133/

相关文章:

java - Java 中的 “sealed interface” 有什么意义?

c++ - 在 main() 之前强制在 C++ 中初始化单例

c# - 静态类是否创建实例? msdn 说我没有,但为什么构造函数呢?

c++ - Voro++ 可以在 2D 中使用吗?

Java 与 Kotlin 接口(interface)声明

c++ - 执行函数调用的顺序?

java - 我收到错误 : class, 接口(interface)或预期的枚举,但我无法弄清楚

c# - 从其他进程向 WPF 单例应用程序发送数据

python - 如何正确访问结构值并将它们传递给函数 - boost::python

c++ - 将函数参数添加到 vector