flatten 20260225
This commit is contained in:
125
tjp/core/singleton/Singleton.hpp
Executable file
125
tjp/core/singleton/Singleton.hpp
Executable file
@@ -0,0 +1,125 @@
|
||||
// TJP COPYRIGHT HEADER
|
||||
|
||||
/**
|
||||
* legal header
|
||||
*
|
||||
* ============================================================================
|
||||
* TJP 10/11/01 Got rid of the constructed singleton, it was essentially
|
||||
* a pointer!
|
||||
*
|
||||
* @author Timothy Prepscius
|
||||
* @created 3/../01
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Singleton.h"
|
||||
|
||||
#include "../containers/FilledArray.hpp"
|
||||
|
||||
namespace timprepscius {
|
||||
namespace core {
|
||||
|
||||
/**
|
||||
* a Singleton container, whose contained instance is constructed on its
|
||||
* first request
|
||||
*
|
||||
* T defines the class pointer type
|
||||
* X defines the allocation class type
|
||||
*/
|
||||
class Singletons
|
||||
{
|
||||
protected:
|
||||
friend class Singleton_;
|
||||
typedef FilledArray<class Singleton_ *> Singletons_;
|
||||
static Singletons_ &singletons();
|
||||
|
||||
public:
|
||||
static void clearAll ();
|
||||
} ;
|
||||
|
||||
class Singleton_
|
||||
{
|
||||
protected:
|
||||
friend class Singletons;
|
||||
virtual void clear () {}
|
||||
|
||||
public:
|
||||
Singleton_ ();
|
||||
virtual ~Singleton_ ();
|
||||
} ;
|
||||
|
||||
template<class T, class X>
|
||||
class Singleton : Singleton_
|
||||
{
|
||||
private:
|
||||
T *instance;
|
||||
|
||||
void clear () override
|
||||
{
|
||||
deleteInstance();
|
||||
}
|
||||
|
||||
public:
|
||||
Singleton()
|
||||
{
|
||||
instance = nullptr;
|
||||
}
|
||||
|
||||
virtual ~Singleton()
|
||||
{
|
||||
deleteInstance();
|
||||
}
|
||||
|
||||
void setInstance (T *instance)
|
||||
{
|
||||
if (this->instance)
|
||||
delete instance;
|
||||
|
||||
this->instance = instance;
|
||||
}
|
||||
|
||||
void verifyInstance()
|
||||
{
|
||||
if (instance==nullptr)
|
||||
{
|
||||
instance = new X();
|
||||
}
|
||||
}
|
||||
|
||||
void deleteInstance()
|
||||
{
|
||||
delete instance;
|
||||
instance = nullptr;
|
||||
}
|
||||
|
||||
T *p()
|
||||
{
|
||||
verifyInstance();
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**********************************************************************
|
||||
* operator overloads to simplify use
|
||||
**********************************************************************/
|
||||
|
||||
template<typename U>
|
||||
operator U *()
|
||||
{
|
||||
return p();
|
||||
}
|
||||
|
||||
T *operator ->()
|
||||
{
|
||||
return p();
|
||||
}
|
||||
|
||||
T &operator *()
|
||||
{
|
||||
return *p();
|
||||
}
|
||||
} ;
|
||||
|
||||
} // namespace
|
||||
} // namespace
|
||||
|
||||
Reference in New Issue
Block a user