Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton rule questions (do not allow to create copy and deserialization)

Tags:

c#

singleton

Reading some article about singleton, I stopped at the point saying: "Do not allow to crate copy of existing instance". I realized that I do not know how would I do that! Could you tell me, please, how could I copy existing instance of class? And the second one: deserializaition. How it could be dangerous?

And for both - how to deny creating copies or deserialization? Thanks

like image 954
Petr Avatar asked Jan 18 '26 01:01

Petr


2 Answers

There are objects with something like a Clone or a Copy method. The idea behind it that it will take the current values of the object and make a new one. The defeats the purpose of a singleton object, because suddenly someone can create a second copy of it.

Another possible way of creating a copy of the object, would be to serialize the object and then de-serialize it to create another copy. So you probably want to mark the singleton object as not serializable.

like image 74
kemiller2002 Avatar answered Jan 20 '26 18:01

kemiller2002


Using serialization/deserialization, you could store the object somewhere and then restore it. That way, you will have two objects. Any changes made to the singleton in the meantime would not be reflected in your new copy.

Afterwards, when you now try to get/set something using the singleton object, you might change it in/get it from the one object or the other. Obviously that can cause all sorts of (sometimes very hard to debug) problems.

EDIT: To create a singleton in C#, see the explanation at http://www.yoda.arachsys.com/csharp/singleton.html

As for serialization: You have to explicitely enable it by including the SerializableAttribute. So simply don't mark your class with it. Note that there is no NonSerializableAttribute for classes, only for fields. It is used when you enabled serialization, but want to deny it for certain parts of the class.

EDIT2: To deny XML-serialization, you could implement IXmlSerializable on the class. Then simply either have empty implementations or throw exceptions from the member methods.

like image 20
Daniel Rose Avatar answered Jan 20 '26 18:01

Daniel Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!