Skip to content

Singleton Pattern

wvdvegt edited this page Jan 14, 2019 · 6 revisions

Singleton Pattern for C#

The following one (Also the pattern used in the Assetmanager) is preferred as it supports a wide range of .Net versions.

(see http://csharpindepth.com/Articles/General/Singleton.aspx):

static readonly YourClass_instance = new YourClass();

// Explicit static constructor tells C# compiler
// not to mark type as beforefieldinit.
static YourClass()
{
}

private YourClass()
{
    //
}

//Visible when reflecting
public static YourClass Instance
{
    get
    {
 return _instance;
    }
}      

Singleton Pattern for Java

In Java the preferred (and simplest) way to create a singleton is to change the class keyword into enum, which forces the compiler to enforce the single instance correctly.

(see https://dzone.com/articles/java-singletons-using-enum):

public enum YourClass {

INSTANCE;

public static YourClass getInstance() {
	return YourClass.INSTANCE;
}

}

Singleton Pattern for C++

Below is the best implementation (when USE_CALL_ONCE is defined a slightly older method using std::once_flag is used). Sources:

Implementing a Thread-Safe Singleton with C++11 Using Magic Statics

Implementing a Thread-safe Singleton with C++11

//
#ifdef USE_CALL_ONCE
#include <mutex>
#endif

using namespace std;
using namespace rage;

#ifdef USE_CALL_ONCE

/// <summary>
/// The asset manager m instance.
/// </summary>
std::unique_ptr<AssetManager> AssetManager::m_instance;

/// <summary>
/// The asset manager m once flag.
/// </summary>
std::once_flag AssetManager::m_onceFlag;
#endif

/// <summary>
/// Gets the instance.
/// </summary>
///
/// <returns>
/// The instance.
/// </returns>
AssetManager& AssetManager::getInstance()
{
#ifdef USE_CALL_ONCE
	std::call_once(m_onceFlag,
		[] {
		m_instance.reset(new AssetManager);
	});
	return *m_instance.get();
#else
	static AssetManager instance;
	return instance;
#endif
}
//

Clone this wiki locally