Openton Singleton Template

public class MySingletonClass
{
  public MySingletonClass()
  {
    _mySingletonObj = Instance();
  }

  public static MySingletonClass Instance()
  {
    if (_mySingletonObj  == null)
    {
      lock (typeof(lockObject))
      {
        if (_mySingletonObj  == null)
          _mySingletonObj  = new MySingletonClass();
      }
    }
    return _mySingletonObj ;
  }
}

MySingletonClass _myObj = new MySingletonClass();

Is this action as singleton with public constructors ..?

thanks

+3
source share
6 answers

No, this is not a singleton - anyone can create multiple instances. (Leaving aside the problem that has already been raised, and the fact that you are using double-check locking).

One of the distinguishing features of the singleton type is that it prevents the construction of more than one instance.

From wikipedia Singleton Pattern :

In software development, a singleton pattern is a design pattern that is used to restrict an instance of a class to a single object.

Ward Cunningham:

A Singleton - :

  • ,

, .

. singleton .

+14

, - , :

  • , , , ...
  • , , . , singleton .
  • , . , .

:

public class MySingletonClass
{
  private readonly object _mySingletonLock = new object();
  private volatile MySingletonClass _mySingletonObj;

  private MySingletonClass()
  {
    // normal initialization, do not call Instance()
  }

  public static MySingletonClass Instance()
  {
    if (_mySingletonObj == null)
    {
      lock (_mySingletonLock)
      {
        if (_mySingletonObj  == null)
          _mySingletonObj = new MySingletonClass();
      }
    }
    return _mySingletonObj;
  }
}

MySingletonClass _myObj = MySingletonClass.Instance();
+4

.NET Optimized code Dofactory. . #.

+3

+1

, , readonly singelton...

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

    static Singleton()
    {
    }

    private Singleton()
    {
    }

    /// <summary>
    /// The public Instance property to use
    /// </summary>
    public static Singleton Instance
    {
        get { return instance; }
    }
}
+1

Singleton :

  • ;
  • .

The Singleton implementation is based on creating a class using a method (or property in .NET) that instantiates this class if it does not already exist. The class constructor must be private to prevent other initialization methods. Also, Singleton should be carefully used in multi-threaded applications, because at the same time, two threads can create two different instances (which violates the singleton pattern).

More information and examples can be found here.

0
source

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


All Articles