Singleton rule questions (do not allow copying and deserialization)

Having carefully read the article on single-user mode, I stopped, saying: "Do not allow copying an existing instance." I realized that I did not know how I would do it! Could you please tell me how can I copy an existing instance of a class? And second: deserialization. How can this be dangerous?

And for both - how to refuse to create copies or deserialization? Thanks

+3
source share
4 answers

There are objects with something like the Clone or Copy method. The idea is that it will take the current values ​​of the object and create a new one. It strikes the target of a single object, because suddenly someone can create a second copy.

Another possible way to create a copy of an object is to serialize the object and then de-serialize it to create another copy. Therefore, you probably want to mark a singleton object as not serializable.

+3
source

Using serialization / deserialization, you can save the object somewhere and then restore it. This way you will have two objects. Any changes made to singleton, meanwhile, will not be reflected in your new copy.

, / - singleton, / . , ( ) .

EDIT: # . http://www.yoda.arachsys.com/csharp/singleton.html

: , SerializableAttribute. . : NonSerializableAttribute, . , , .

EDIT2: XML-, IXmlSerializable . , -.

+3

:

/, , .

#, : [Serializable]

/ , , ( ), . , .

(, ) 13 " #". .

:

public class SingletonExample
{
    private static readonly SingletonExample singleInstance
    static SingletonExample()
    {
        singleInstance = new SingletonExample();
    }
    public static SingletonExample Instance
    {
        get { return singleInstance; }
    }
    private SingletonExample()
    {
    }
}
+2

, , , .Clone() .Copy(). , .MemberwiseClone(), .

. , [SerializableAttribute()] . , XmlSerialzation, . , , , .

, , XmlDeserializer , . , 4.0, . [XmlIgnore] yoru .

, , , , , . - / , , / . , , . , - , /, .

+2

Source: https://habr.com/ru/post/1743178/


All Articles