gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:39:52 25 4
gpt4 key购买 nike

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

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

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

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

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

问题:

  1. 每当我需要使用类时,我应该从程序的其余部分调用 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
  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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com