我有一个带有纯虚方法的接口(interface)类Interface
。
class Interface
{
public:
virtual void DoSomething() = 0;
}
此外,还有一个实现该接口(interface)的类Implementation
。
class Implementation : public Interface
{
void DoSomething();
}
在我的程序中,我需要有一个实现/接口(interface)
对的单例(单个实例)。程序中存在许多对 Implementation/Interface
类,但一个 Interface
类的 Implementation
类很少。
问题:
每当我需要使用类时,是否应该从程序的其余部分调用
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?"
使用接口(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/