jeudi 19 juillet 2018

Examples of singleton implementation

I have two questions about singleton implementation.
Here is two examples of create a singleton.
There is a preferable / better one? Some pros and cons?

First one:

private static readonly SingletonClass instance = new SingletonClass();
public static SingletonClass Instance
{
   get
   {
        return instance;
   }
}

The second one:

private static SingletonClass instance;
public static GetInstance
{
    get
    {
       if(instance == null)
       {
         instance = new SingletonClass();
       }
       return instance;
    }
}

What is more efficient? There is an actual different?
The check if instance equals to null is expensive?

My second question is what about if I have a property inside a class (and this class it isn't a singleton), can I implement it like a singleton (good / bad practice)?
For example:

public class MyClass
{
    private DataTable _dt;
    public DataTable GetDt
    {
        get
        {
            if (_dt == null)
            {
                _dt = new DataTable();
                _dt.Columns.Add("Column1", typeof(string));
                _dt.Columns.Add("Column2", typeof(string));
                _dt.Rows.Add(new string[] { "cell1", "cell2" });
            }
            return _dt;
        }
    }
}

Or should I "export" this DataTable to a class and create a singleton class with this property as a member.

Thanks

Aucun commentaire:

Enregistrer un commentaire