C++ In Theory: The Singleton Pattern, Part I - A Logging Class
(Page 2 of 5 )
Here is a simple class that collects strings and can write them to a file. This class will represent the log we aim to implement in this article.
// log.h
#ifndef __LOG_H
#define __LOG_H
#include <list>
#include <string>
class Log {
public:
void Write(char const *logline);
bool SaveTo(char const *filename);
private:
std::list<std::string> m_data;
};
#endif // __LOG_H
// eof
// log.cpp
#include <fstream>
using namespace std;
#include “log.h”
void Log::Write(char const *logline)
{
m_data.push_back(logline);
}
bool Log::SaveTo(char const *filename)
{
ofstream file(filename, ios::out);
list<string>::iterator it;
list<string>::iterator lastIt=m_data.end();
for (it=m_data.begin(); it!=lastIt; ++it)
file << *it << endl;
file.close();
}
// eof
We are going to alter the behavior of this class to ensure that only one instantiation of it can be created during the lifetime of an application using it. This will cause all strings provided in calls to Log::Write, to end up in a single list (Log::m_data) which can be written to a single file when Log::Write is called.
Next: Statics are not Singletons >>
More C++ Articles
More By J. Nakamura