See what's going on with flipcode!




This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Singleton Class
  Submitted by



Here is a singleton class that allows you to have only one instance of an object. Good for multi-threaded environments that require access to shared data and functionality ie Game Window, Network Transport Managers, AI Managers, etc.. The list goes on. Have fun,
Dave

Currently browsing [singleton.zip] (2,177 bytes) - [Singleton.h] - (276 bytes)

/* Dave Pallot */
/* 2000 */

class Singleton { private: Singleton(); virtual ~Singleton();

public: static Singleton* m_instance; static Singleton* instance(); static void destroy();

public: void func1(); int func2();

private: char* m_buffer; };

Currently browsing [singleton.zip] (2,177 bytes) - [Singleton.cpp] - (631 bytes)

/* Dave Pallot */
/* 2000 */

#include "Singleton.h" #include <iostream>

Singleton* Singleton::m_instance = 0;

Singleton::Singleton() { m_buffer = new char[40]; ::memset(m_buffer, 0, 40); }

Singleton::~Singleton() { delete[] m_buffer; }

Singleton* Singleton::instance() { if (m_instance == 0) { m_instance = new Singleton(); }

return m_instance; }

void Singleton::destroy() { delete m_instance; m_instance = 0; }

void Singleton::func1() { ::strcpy(m_buffer, "Func 1 called");; }

int Singleton::func2() { std::cout << m_buffer << std::endl; return 0; }


Currently browsing [singleton.zip] (2,177 bytes) - [SingletonClass.cpp] - (272 bytes)

/* Dave Pallot */

#include "singleton.h"

int main(int argc, char* argv[]) { // Create a singleton Singleton::instance();

Singleton::instance()->func1(); Singleton::instance()->func2();

// Kill the singleton Singleton::destroy();

return 0; }


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.