单例和接口实现
Singleton and Interface implementation
我有一个带有纯虚方法的接口 class Interface
。
class Interface
{
public:
virtual void DoSomething() = 0;
}
另外,还有一个classImplementation
实现了接口
class Implementation : public Interface
{
void DoSomething();
}
在我的程序中,我需要有一个 Implementation/Interface
对的单例(单个实例)。程序中有很多对Implementation/Interface
classes,但是很少Implementation
classes一对Interface
class.
问题:
每当我需要使用 class 时,我应该从程序的其余部分调用 Interface
或 Implementation
class 吗?
我究竟应该怎么做?
//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;
}
更好的选择是根本不使用单例,而是让您的代码准备好专门在 Interface
上运行:
class Interface {
// ...
};
class Impl : public Interface {
// ...
};
class Client {
Interface& if_;
public:
Client(Interface& if__) : if_(if__) {}
// ...
}
int main() {
Impl impl;
Client client(impl);
};
我有一个带有纯虚方法的接口 class Interface
。
class Interface
{
public:
virtual void DoSomething() = 0;
}
另外,还有一个classImplementation
实现了接口
class Implementation : public Interface
{
void DoSomething();
}
在我的程序中,我需要有一个 Implementation/Interface
对的单例(单个实例)。程序中有很多对Implementation/Interface
classes,但是很少Implementation
classes一对Interface
class.
问题:
每当我需要使用 class 时,我应该从程序的其余部分调用
Interface
或Implementation
class 吗? 我究竟应该怎么做?//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;
}
更好的选择是根本不使用单例,而是让您的代码准备好专门在 Interface
上运行:
class Interface {
// ...
};
class Impl : public Interface {
// ...
};
class Client {
Interface& if_;
public:
Client(Interface& if__) : if_(if__) {}
// ...
}
int main() {
Impl impl;
Client client(impl);
};