4

We have some legacy code that has a bunch of singletons all over the place (written in C#).

The singleton is a fairly "classic" implementation of the pattern:

public class SomeSingleton
{
    private static SomeSingleton instance;

    private SomeSingleton()
    {
    }

    public static SomeSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new SomeSingleton();
            }

            return instance;
        }
    } 
}

Note that thread safety is not a concern, so no locks are used.

In order to make the code more testable, and without making too many modifications, I'd like to modify this code to delegate the creation of the singleton instance in another class (a factory or similar pattern).

This can assist in creating a "test" instance for testing purposes, or the real version, as it is used now.

Is this a common practice? I could not find any reference to such pattern being used.

7
  • 2
    Depending on how much refactoring you're willing to do, you can kill the singleton altogether and inject a factory. Then the factory can manage whether it wants to give every class the same instance Commented Apr 28, 2015 at 12:21
  • 1
    Alternatively, keep the singletons and mock them out at runtime using a tool like Fakes
    – gbjbaanb
    Commented Apr 28, 2015 at 12:30
  • 1
    Some of these tools have a hard time faking static properties or stuff like that. I will look into it though !
    – liortal
    Commented Apr 28, 2015 at 12:38
  • 1
    @liortal Fakes is a great tool, it solves the problem of having to fudge your code just to make the testing framework happy. It basically hacks the binary with a replacement class or function so you build your code as normal, and then use it to swap out the normal function with your test one. A bit like a hacker replacing game protection routines. It an even be used with built-in statics like DateTime!
    – gbjbaanb
    Commented Apr 28, 2015 at 12:55
  • @gbjbaanb one thing i didn't mention is that we're using C# but not in a MSFT environment (we are using Unity and Mono for game development). Not sure Fakes would work in that context, but i will check!
    – liortal
    Commented Apr 28, 2015 at 13:13

2 Answers 2

3

In the comments you say you are using Unity and Mono for game development. I am guessing that means Unity3D not Microsoft Unity. As such I would recommend that you ditch the singleton pattern that you are following and instead use dependency injection. I believe you can use Zenject with the unity3d framework.

The singleton class would be modified to be an instance of an interface like:

public class IImportantInterface
{
  DoSomethingImportant();
}

public class MySingletonImplementation: IImportantInterface
{
  public void DoSomethingImportant()
  {
    Console.WriteLine("This is Important!");
  }
}


public class DoImportantStuff
{
    private readonly IImportantInterface _ImportantInterface;

    public DoImportantStuff(IImportantInterface importantInterface )
    {
    _importantInterface = importantInterface;
    }


    public void DoSomething()
    {
    _importantInterface.DoSomethingImportant();
    }

}

Then in you startup logic you can register a singleton instance with Zenject:

Container.Bind<IImportantInterface>().ToSingle<MySingletonImplementation>(); 

A good blog post about this concept can be found here: http://www.unityninjas.com/code-architecture/dependency-injection/

0

This calls for inversion of control. Just start by adding an interface to SomeSingleton say ISomeSingleton. Then all consumers of ISomeSingleton will just get an constructor parameter of ISomeSingleton.

Example:

public class Consumer1 {
    readonly ISomeSingleton _mySingleton;
    public Consumer1(ISomeSingleton mySingleton) {_mySingleton = mySingleton;}
}

public interface ISomeSingleton{//All your methods you ned.}

public class SomeSingleton : ISomeSingleton
{
    private static SomeSingleton instance;

    public SomeSingleton() // constructor is now public
    {
    }

    public static SomeSingleton Instance // todo remove this when all consumers follow inversino of control pattern.
    {
        get
        {
            if (instance == null)
            {
                instance = new SomeSingleton();
            }

        return instance;
        }
    } 
}

When no consumer calls the SomeSingleton directly you can just remove it. This allows you to make the change at your own pace.

Now you just need to figure out how to instantiate SomeSingleton. You can just do this manually or you can start using an IOC container of you feel like it.

In testing you can just create a different implementation of ISomeSingleton.

3
  • Not sure I understand "Then all consumers of ISomeSingleton will just get an constructor parameter of ISomeSingleton."
    – liortal
    Commented Apr 28, 2015 at 12:39
  • @liortal - instead of accessing the global directly, refactor your code to take an instance instead.
    – Telastyn
    Commented Apr 28, 2015 at 13:04
  • @Telastyn that means i have to refactor all code that access this singleton. This is a big change, one that i'm trying to avoid at the moment.
    – liortal
    Commented Apr 28, 2015 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.