cpp_photon/include/util/Singleton.hpp

115 lines
2.2 KiB
C++
Raw Normal View History

2005-02-27 05:50:54 +00:00
//This file is part of Photon (http://photon.sourceforge.net)
//Copyright (C) 2004-2005 James Turk
//
// Author:
// James Turk (jpt2433@rit.edu)
//
// Version:
2005-03-01 07:51:23 +00:00
// $Id: Singleton.hpp,v 1.4 2005/03/01 07:51:23 cozman Exp $
2005-02-27 05:50:54 +00:00
#ifndef PHOTON_UTIL_SINGLETON_HPP
#define PHOTON_UTIL_SINGLETON_HPP
#include <memory>
#include <boost/utility.hpp>
namespace photon
{
namespace util
{
2005-03-01 07:51:23 +00:00
// Class: Singleton
// Template class for singleton pattern. Is non-copyable to enforce
// correct behavior.
//
// Defining a Singleton:
// (code)
// YourClass : public Singleton<Class>
// {
// // class specific data
//
// // Singleton-required code
// private:
// // Singleton-required code
// YourClass();
// ~YourClass();
//
// friend class util::Singleton<YourClass>;
// friend class std::auto_ptr<YourClass>;
// };
// (end)
//
// Using The Singleton:
// (code)
// YourClass::initialize();
// YourClass& yc(YourClass::getInstance());
//
// // use yc
//
// YourClass::destroy(); //optional
// (end)
2005-02-27 05:50:54 +00:00
template<class T>
class Singleton : public boost::noncopyable
{
public:
2005-03-01 07:51:23 +00:00
// Function: initialize
// Initialize the instance of the singleton, must be done explicitly.
2005-02-27 07:43:37 +00:00
static void initialize();
2005-02-27 05:50:54 +00:00
2005-03-01 07:51:23 +00:00
// Function: destroy
// Destroy the instance of the singleton, can be done explicitly if order
// of destruction matters. Will be done automatically if not done.
2005-02-27 07:43:37 +00:00
static void destroy();
2005-02-27 05:50:54 +00:00
2005-03-01 07:51:23 +00:00
// Function: getInstance
// Get a reference to the instance of the derived class.
2005-02-27 07:43:37 +00:00
static T& getInstance();
2005-02-27 05:50:54 +00:00
2005-03-01 07:51:23 +00:00
protected:
2005-02-27 05:50:54 +00:00
virtual ~Singleton()=0;
private:
static std::auto_ptr<T> instance_;
};
// template implementation
template<class T>
Singleton<T>::~Singleton()
{
}
template<class T>
2005-02-27 07:43:37 +00:00
void Singleton<T>::initialize()
2005-02-27 05:50:54 +00:00
{
assert(instance_.get() == 0);
2005-02-27 07:43:37 +00:00
2005-02-27 05:50:54 +00:00
instance_ = std::auto_ptr<T>(new T);
}
template<class T>
2005-02-27 07:43:37 +00:00
void Singleton<T>::destroy()
2005-02-27 05:50:54 +00:00
{
assert(instance_.get() != 0);
2005-02-27 07:43:37 +00:00
2005-02-27 05:50:54 +00:00
instance_.reset();
}
template<class T>
2005-02-27 07:43:37 +00:00
T& Singleton<T>::getInstance()
2005-02-27 05:50:54 +00:00
{
assert(instance_.get() != 0);
2005-02-27 07:43:37 +00:00
2005-02-27 05:50:54 +00:00
return *instance_;
}
template<class T>
std::auto_ptr<T> Singleton<T>::instance_(0);
}
}
#endif //PHOTON_UTIL_SINGLETON_HPP