#785 – The Singleton Pattern

Singleton is a design pattern that you can use when you have a situation where you want to limit a particular class to have at most one instance.

A singleton behaves similarly to a static class in C#, but has some advantages, in that it behaves as a traditional object.  (E.g. Can implement an interface, or be passed to a method).

Here’s a common (thread-safe) pattern for implementing a singleton in C#.

    public sealed class DogFactory
    {
        // Instance created when first referenced
        private static readonly DogFactory instance = new DogFactory();

        // Prevent early instantiation due to beforefieldinit flag
        static DogFactory() { }

        // Prevent instantiation
        private DogFactory() { }

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

        // Actual methods go here, e.g.:
        public Dog CreateDog(string name)
        {
            return new Dog(name);
        }
    }

To use the singleton, you use the Instance property:

            Dog d = DogFactory.Instance.CreateDog("Bob");
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #785 – The Singleton Pattern

  1. Pingback: #786 – A Lazier Singleton Pattern | 2,000 Things You Should Know About C#

  2. Pingback: #948 – Using Lazy to Implement the Singleton Pattern | 2,000 Things You Should Know About C#

  3. Pascal says:

    If a second line is added:
    Dog d2 = DogFactory.Instance.CreateDog(“Sam”);
    It creates a second dog, right? So what is the benefit please?

    • Sean says:

      You can create as many Dog instances as you like–that’s what the DogFactory class does. But you’re only allowed to create a single instance of the DogFactory–that’s the class that follows the singleton pattern.

  4. code2share says:

    Thanks,. how to handle multi threaded scenario, no need to lock it?

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: