Bhavya

Code -> Break -> Fix -> Blog

Implementing Singleton Pattern with/without Lazy instantiation

Leave a comment

Implement Singleton with:

1. Thread-safe (not using Locks)

2. Not Lazy


public sealed class MySingleton
{
private static readonly MySingleton instance;

static MySingleton()
{
instance = new MySingleton();
}

private MySingleton()
{
}

public static MySingleton Instance
{
get
{
return instance;
}
}
}

Implement Singleton with:

1. Full Lazy

2. Thread-safe (not using Locks)

3. Not using System.Lazy<T> type.

4. .NET 3.5 and below.


public sealed class MySingleton
{
private class Nested
{
static Nested()
{
instance = new MySingleton();
}

internal static readonly MySingleton instance;
}

private MySingleton()
{
}

public static MySingleton Instance
{
get
{
return Nested.instance;
}
}
}

Implementation Singleton with:

1. Full Lazy

2. Thread-safe (not using Locks)

3. Using System.Lazy<T> type.

4. .NET 4.0 and above.


public sealed class MySingleton
{
private static readonly Lazy<MySingleton> instance = new Lazy<MySingleton>(() => new MySingleton());

private MySingleton()
{
}

public static MySingleton Instance
{
get
{
return instance.Value;
}
}
}

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