Home arrow C++ arrow Page 2 - C++ In Theory: The Singleton Pattern, Part I

C++ In Theory: The Singleton Pattern, Part I

Have you ever wondered how to implement a class with simple logging functionality? J. Nakamura explains how to do it in a way that makes use of the Singleton pattern.

Author Info:
By: J. Nakamura
Rating: 4 stars4 stars4 stars4 stars4 stars / 87
January 18, 2005
  1. · C++ In Theory: The Singleton Pattern, Part I
  2. · A Logging Class
  3. · Statics are not Singletons
  4. · The Gamma Singleton
  5. · The Meyers Singleton

print this article

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 {
  void Write(char const *logline);
  bool SaveTo(char const *filename);
  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)

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;

// 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.

blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials