c++ - Singleton and Interface implementation -
i have interface class interface pure virtual methods.
class interface { public: virtual void dosomething() = 0; } also, there class implementation implements interface.
class implementation : public interface { void dosomething(); } in program need have singleton (single instance) of implementation/interface pair. there many pairs of implementation/interface classes in program, few implementation classes 1 interface class.
questions:
should invoke
interfaceorimplementationclass rest of program whenever need use class? how should so?//interface needs know implementation interface * module = interface::instance(); //no enforcement of interface implementation * module = implementation::instance(); //a programmer needs remember implementation , interface names interface * module = implementation::instance(); //may there better wayhow should method
instance()like?
"1) should invoke interface or implementation class rest of program whenever need use class? how should so?"
use interface, less clutter code implementation::instance() calls:
interface& module = implementation::instance(); // ^ note reference, assignment , copy won't work.
"2) how should method instance() like?"
the common consensus use scott meyer's approach:
implementation& instance() { static implementation theinstance; return theinstance; } the better alternative not use singleton @ make code ready operate on 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); };
Comments
Post a Comment