I have an interface class Interface
with pure virtual methods.
class Interface
{
public:
virtual void DoSomething() = 0;
}
"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);
};