单例和接口实现 [英] Singleton and Interface implementation
问题描述
我有一个接口类接口
与纯虚拟方法。
class Interface
{
public:
virtual void DoSomething()= 0;
}
此外,还有一个类 Implementation $
类实现:public Interface
{
void DoSomething );
}
在我的程序中,我需要一个Singleton c $ c>实现/接口对。在程序中有许多对 Implementation / Interface
类,但很少有 Implementation
类用于一个
>
我应该从程序的其余部分调用接口
或实现
每当我需要使用类吗?
我应该怎么做呢?
//接口需要了解实现
Interface * module = Interface :: Instance
//没有强制执行接口
实现* module = Implementation :: Instance();
//程序员需要记住实现和接口名称
Interface * module = Implementation :: Instance();
//可能有更好的方法
如果方法 Instance()
看起来像?
1)当我需要使用类时,我应该从程序的其余部分调用Interface还是Implementation类?
使用接口,这样就不会使您的代码乱码 Implementation :: Instance )
调用:
module = Implementation :: Instance();
// ^
请注意,引用,分配和复制将不起作用。 p>
2)方法Instance()应该如何?
普遍的共识是使用 Scott Meyer的方法:
实施& Instance(){
static实现theInstance;
return theInstance;
}
单独使用单例,但使代码准备好在接口
上独占操作:
class Interface {
// ...
};
class Impl:public Interface {
// ...
};
类客户端{
接口&如果_;
public:
客户端(interface& if__):if_(if__){}
// ...
}
int main
Impl impl;
客户端(impl);
};
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:
Should I invoke
Interface
orImplementation
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
How should the method
Instance()
look like?
"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);
};
这篇关于单例和接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!