Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / C#
Tip/Trick

common Singleton Pattern implementation using Generic

Rate me:
Please Sign up or sign in to vote.
2.67/5 (3 votes)
17 Oct 2011CPOL 20.1K   7   7
Customized implementation of the Singleton pattern using Generics.
I read this link content(Jon Skeet) and implement the singleton pattern in a class that can be used for any object that you want to be singleton.

http://csharpindepth.com/Articles/General/Singleton.aspx[^]

Generic implementation of Jon Skeet's is here:
C#
public class Singleton<T> where T : new()
{
    private static readonly Lazy<T> lazy = new Lazy<T>(() => new T());

    Singleton()
    {
    }

    public static T Instance
    {
        get
        {
            return lazy.Value;
        }
    }
}


For example, we have a service:

C#
public class SampleService
{
    public List<MyItemType> GetItems()
    {
        var dataList = new List<MyItemType>();
        //do some works and fill dataList
        return dataList;
    }
}


Everywhere I want to use SampleService, I can get a singleton instance in this way:

C#
var serviceInstance = Singleton<sampleservice>.Instance;

var myList = serviceInstance.GetItems();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer mp3lyric.us
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 4 good Pin
Jai Mallesh10-Oct-11 19:38
Jai Mallesh10-Oct-11 19:38 
GeneralProbably needs to be tagged as .Net 4 as it is using <code>L... Pin
Reiss5-Oct-11 3:30
professionalReiss5-Oct-11 3:30 
GeneralRe: thanks reiss, now its be tagged as .Net 4 too Pin
omid rezaei hanjani17-Oct-11 23:42
omid rezaei hanjani17-Oct-11 23:42 
Generalthanks richard, I changed that Pin
omid rezaei hanjani4-Oct-11 22:01
omid rezaei hanjani4-Oct-11 22:01 
GeneralThis code is not fool proof. If I wish, I can directly creat... Pin
A. Rajesh Kumar3-Oct-11 20:21
A. Rajesh Kumar3-Oct-11 20:21 
GeneralReason for my vote of 2 The phrase "my implementation" impli... Pin
Richard Deeming3-Oct-11 9:59
mveRichard Deeming3-Oct-11 9:59 
GeneralRe: Thanks Richard, I changed "my implementation" to "generic im... Pin
omid rezaei hanjani4-Oct-11 23:51
omid rezaei hanjani4-Oct-11 23:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.