Best implementation of Singleton Pattern

il_fullxfull.281865652_50

File Singleton.h

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include <cassert>

template<typename T> class Singleton
{
public:
	Singleton()
	{
		assert(!m_spSingleton);
		int offset = (int)(T*)1 - (int)(Singleton<T>*)(T*)1;
		m_spSingleton = (T*)( (int)this + offset );
	}
	~Singleton()
	{
		assert(m_spSingleton);
		m_spSingleton = 0;
	}
	static T& GetSingleton()
	{
		assert(m_spSingleton);
		return *m_spSingleton;
	}
	static T* GetSingletonPtr()
	{
		return m_spSingleton;
	}
private:
	static T* m_spSingleton;
};

template<typename T> T* Singleton<T>::m_spSingleton = 0;

#endif

To convert any class into a singleton, e.g class TextureMgr:

#include "Singleton.h"

#define g_rTextureMgr TextureMgr::GetSingleton()
#define g_pTextureMgr TextureMgr::GetSingletonPtr()

class TextureMgr : public Singleton<TextureMgr>
{
public:
	int GetTexByName(const char* texName);
};

How to use:

void GameInit()
{
	new TextureMgr();
}

void GameUpdate()
{
	int texId = g_rTextureMgr.GetTexByName("test.tga");
	// ...
}

void GameDestroy()
{
	delete g_pTextureMgr;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s