Click here to Skip to main content
11,431,171 members (67,024 online)
Click here to Skip to main content

common Singleton Pattern implementation using Generic

, 18 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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:
    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:

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:

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)

Share

About the Author

omid rezaei hanjani
Software Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 18 Oct 2011
Article Copyright 2011 by omid rezaei hanjani
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid