问题
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:
"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);
};
来源:https://stackoverflow.com/questions/30557133/singleton-and-interface-implementation