How to make Singleton a lazy instance of a class?

I have a class that is lazy created by another library. I do not control this library code, but still have to be sure that it cannot create more than one instance of my class.

Is it possible? as?

+3
source share
2 answers

Some simple solutions to this issue hide some problems, for a complete understanding of this issue, I recommend reading the following article

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

What ends with the optimal solution

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}
+4
source

, , , , , . , factory , , .

-, singleton. MyObjectProxy, MyObject.

public class MyObject {

    internal MyObject() {
    }

    private int _counter;

    public int Increment() {
        return Interlocked.Increment(ref _counter);
    }

}

public class MyObjectProxy {

    private static readonly MyObject _singleton = new MyObject();

    public MyObjectProxy() {
    }

    public int Increment() {
        return _singleton.Increment();
    }

}
+1

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


All Articles