February 23, 2020

Break singleton using c#

public class Person
{
    private static Person _person = null;

    private Person()
    { }

    public string Name { get; }

    public static Person PersonObj
    {
        get
        {
            if (_person == null)
                _person = new Person();

            return _person;
        }
    }
}
now i can create two instances of this class by Serialization.
static void Main(string[] args)
{
    Person p = Person.PersonObj;
    string sss = Newtonsoft.Json.JsonConvert.SerializeObject(p);
    Person p1 = JsonConvert.DeserializeObject<Person>(sss);    
    if (p != p1)
    {
           // insert here 
    }
} 
Now after Serialization I have two different object. As the class is singleton how it can have two different objects ?
Discussion :


This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created. 
A singleton is a programming concept - not a language feature. Its perfectly possible to create code that creates instances of classes that - in theory - should only be created by a singleton factory. You don't even need to use serialization to achieve that - just use Activator.CreateInstance().
It might be helpful also to consider that your class constructor also doesn't have to get called; sure, if your call new MyClass() it will do, but deserialization doesn't have to call the constructor. Serialization as a concept stores and rehydrates the state of a class instance; so it doesn't need to obey other class instantiation concepts, like constructor scope or constructor logic.

Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we ceate clone of a singleton object, then it wil create a copy that is there are two instances of a singleton class, hence the class is no more singleton.

No comments: