Reputation: 13575
I'm developing a GUI application. I have a main window. The main window has an information window to record some basic information of current operations such as what is doing and how long does it take. The code is like the following:
class InfoWindow
{
public:
InfoWindow();
void Record(const string& info);
};
class MainWindow
{
public:
void OperationInMainWindow()
{
// Perform the operation.
...
// Record the operation information (okay here since m_infoWindow is
// accessible.
m_infoWindow.Record(...);
}
private:
InfoWindow m_infoWindow;
// Many other windows. Other windows have also operations whose information
// need to record. And getting worse, the other windows have children
// windows who have to record operation information in the main window's
// info window.
OtherWindow1 m_otherWindow1; //
OtherWindow2 m_otherWindow2;
...
};
How to make the information recording easier? I try using singleton for the info window but not very satisfied because the life of the info window should be controlled by the main window. Thanks a lot!!!
Upvotes: 1
Views: 48
Reputation: 47954
What you've described is a form of logging, and logging is commonly done with a singleton object. (And it's one of the very few reasonable uses of a singleton.)
You could have a singleton logging object that directs messages to the current InfoWindow. So you'd create your logging object, and by default, it just throws the messages away. When the InfoWindow is created, it "registers" itself with the logging object. From then on, the logging object directs the messages to the InfoWindow. When the InfoWindow is destroyed, it unregisters with the logging object.
The nice thing about that is you could use the singleton logging object to also copy strings to a log file, or a console window, or anything else.
You could get even more general and decoupled by using a publisher/subscriber model, but that's possibly more elaborate than what you want and need at this time.
Upvotes: 1