I l@ve RuBoard |
![]() ![]() |
6.1 Static Data + Static Functions != SingletonAt first glance, it seems that the need for Singleton can be easily obviated by using static member functions and static member variables: class Font { ... }; class PrinterPort { ... }; class PrintJob { ... }; class MyOnlyPrinter { public: static void AddPrintJob(PrintJob& newJob) { if (printQueue_.empty() && printingPort_.available()) { printingPort_.send(newJob.Data()); } else { printQueue_.push(newJob); } } private: // All data is static static std::queue<PrintJob> printQueue_; static PrinterPort printingPort_; static Font defaultFont_; }; PrintJob somePrintJob("MyDocument.txt"); MyOnlyPrinter::AddPrintJob(somePrintJob); However, this solution[1] has a number of disadvantages in some situations. The main problem is that static functions cannot be virtual, which makes it difficult to change behavior without opening MyOnlyPrinter's code.
A subtler problem of this approach is that it makes initialization and cleanup difficult. There is no central point of initialization and cleanup for MyOnlyPrinter's data. Initialization and cleanup can be nontrivial tasks—for instance, defaultFont_ can depend on the speed of printingPort_. Singleton implementations therefore concentrate on creating and managing a unique object while not allowing the creation of another one. |
I l@ve RuBoard |
![]() ![]() |