HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Singleton implementation using generics

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericsimplementationsingletonusing

Problem

I did this as an exercise just to practice/improve using generics.

Independent of how useful this implementation of a Singleton is, how is my coding in terms of using generics and any other aspect of class design of code style?

```
void Main()
{
var a = Singleton.Value;
var b = Singleton.Value;
var c = Singleton.Value;
var d = Singleton.Value;
var e = Singleton.Value;
var f = Singleton.Value;
var g = Singleton.Value;
var h = Singleton.Value;
}

class SingletonBase
{
protected static object Locker = new LockerObject();
}

class Singleton : SingletonBase where T : new()
{
static T StaticT;

public static T Value
{
get
{
lock (Locker)
{
if(StaticT == null)
{
StaticT = Activator.CreateInstance>().Create();
}
else
{
Console.WriteLine ("Singleton::Value" + typeof(T).Name + " is already created");
}
}
return StaticT;
}
}
}

class Singleton : SingletonBase where T : new() where F : IFactory, new()
{
static T StaticT;

public static T Value
{
get
{
lock (Locker)
{
if(StaticT == null)
{
StaticT = new F().Create();
}
else
{
Console.WriteLine ("Singleton::Value" + typeof(T).Name + " is already created");
}
}
return StaticT;
}
}
}

class LockerObject
{
Guid myGUID;
public LockerObject()
{
this.myGUID = Guid.NewGuid();
Console.WriteLine ("New LockerObject " + this.myGUID.ToString());
}
}

interface IFactory
{
T Create();
}

class Factory : IFactory where T : new()
{
public T Create()
{
Console.WriteLine ("Factory::Create()");
return new T(

Solution

About your locking strategy to create the singleton, I would use a double check to avoid too much locking:

if(x)
{
    lock(Locker)
        if(x) //again once we got the lock
            DoStuff();
} 
else 
{
    FooBar();
}


Like this, you will hopefully use the lock only once when you first call the instance.

Code Snippets

if(x)
{
    lock(Locker)
        if(x) //again once we got the lock
            DoStuff();
} 
else 
{
    FooBar();
}

Context

StackExchange Code Review Q#11978, answer score: 3

Revisions (0)

No revisions yet.