0

I have a question in my mind that there is an issue with Singleton Pattern. Suppose i make an object of Singleton class and serialize it.

Now I restart the server.

Suppose I have again created the instance of Singleton class and then de-serialize it. It creates two objects.

This breaks the Singleton pattern. How do you solve it so that 2nd object is not created.

Howli
  • 11,925
  • 19
  • 46
  • 70

1 Answers1

0

A correct implementation of a singleton will not create more than one instance. How to do this will be somewhat language-dependent. See , e.g., http://csharpindepth.com/Articles/General/Singleton.aspx

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
} 
Mike Stockdale
  • 5,246
  • 3
  • 28
  • 33