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

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 / 86
January 18, 2005
TABLE OF CONTENTS:
  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
SEARCH DEVARTICLES

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.


blog comments powered by Disqus
C++ ARTICLES

- 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 
Support 

Developer Shed Affiliates

 




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