|
// singleton.h
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 19.07.2001 : Tim Hagemann
// - created
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef singletonH
#define singletonH
#include <memory>
template <class T> class CreateImplementation
{
public:
static T *CreateNew(void)
{
return new T;
}
};
template <class T,typename CreatePolicy = CreateImplementation<T> > class Singleton
{
public:
//--- d'tor is public. Will shutdown the implementation implicitly
~Singleton()
{
Shutdown();
}
// -- acessors
// --- static Get will create the singleton using an auto-ptr
static Singleton &Get()
{
if (m_InstancePtr.get() == NULL) m_InstancePtr = std::auto_ptr<Singleton>(new Singleton);
return *m_InstancePtr;
}
// --- static Get will create the singleton using an auto-ptr
static bool IsAvailable(void)
{
if (!m_InstancePtr.get()) return false;
return (m_InstancePtr->m_Implementation != NULL);
}
// --- this will create the implementation implicitly
T *operator -> ()
{
Startup();
return m_Implementation;
}
// --- this will create the implementation explicitly
void Startup(void)
{
if (m_Implementation == NULL)
{
m_Implementation = CreatePolicy::CreateNew();
}
}
// --- this will shutdown the implementation
void Shutdown(void)
{
if (m_Implementation)
{
delete m_Implementation;
m_Implementation = NULL;
}
}
void Restart(void)
{
Shutdown();
Startup();
}
protected:
//--- c'tor,copy-c'tor and assignment are forbidden
Singleton()
{
m_Implementation = NULL;
}
Singleton(const Singleton ©)
{
ESG_ASSERT(false);
}
void operator = (const Singleton ©)
{
ESG_ASSERT(false);
}
// --- auto_ptr of singleton class. Will remove the singleton on app shutdown
static std::auto_ptr<Singleton> m_InstancePtr;
T *m_Implementation;
};
#endif
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Being a software developer since 1992, I have seen many different programming languages, operating systems and methodologies.
My primary technical interest are C++ and Windows-Programming, but due to my work as a project manager, I have even seen J2EE.
My everyday work since a couple of years is leading software development teams, mostly in an agile way.