lundi 31 octobre 2022

Two singletons or Two members of a singleton?

In a C# app, a thread-safe singleton can be implemented by Lazy<T>.

In my app (regarded as a system), if I would like to have two or more global settings (a & b) which also need thread-safe, which solution is better?

  1. One singleton has two settings:
class A
{
    public int a { get; set; }
}

class B
{
    public int b { get; set; }
}

class Singleton
{
    static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());
    public static Singleton Instance { get { return instance.Value; } }

    Singleton()
    { }

    public A A { get; } = new A();
    public B B { get; } = new B();
}

static class Test
{
    public static void Main()
    {
        TaskFactory.StartNew(() =>
        {
            while (true) Singleton.Instance.A.a = 1;
        });
        TaskFactory.StartNew(() =>
        {
            while (true) Singleton.Instance.B.b = 2;
        });
    }
}
  1. Two different singletons:
class SingletonA
{
    static readonly Lazy<SingletonA> instance = new Lazy<SingletonA>(() => new SingletonA());
    public static SingletonA Instance { get { return instance.Value; } }

    public int a { get; set; }
}

class SingletonB
{
    static readonly Lazy<SingletonB> instance = new Lazy<SingletonB>(() => new SingletonB());
    public static SingletonB Instance { get { return instance.Value; } }

    public int b { get; set; }
}

static class Test
{
    public static void Main()
    {
        TaskFactory.StartNew(() =>
        {
            while (true) SingletonA.Instance.a = 1;
        });
        TaskFactory.StartNew(() =>
        {
            while (true) SingletonB.Instance.b = 2;
        });
    }
}

My current implementation is Solution 1.

Aucun commentaire:

Enregistrer un commentaire