I’ve got a singleton class:
public class Widget
{
private Mapper mapper;
private static Widget SINGLETON;
private Widget(Mapper map)
{
setMapper(map);
}
public Widget getInstance()
{
if(SINGLETON == null)
SINGLETON = new Widget(???);
return SINGLETON;
}
}
Not only do I not understand how to pass SINGLETON a Mapper in its private constructor, I’m not seeing how I can use dependency injection to properly set the singleton up. Say Mapper is an interface. Perhaps under “normal” execution I want to pass SINGLETON a StandardMapper instance, but while unit testing, I want to pass it a MockMapper.
Thanks in advance for any pointers!
Pass an argument to
getInstance(), perhaps providing one with and without aWidget.If you’re using a DI framework there are other options, but you don’t mention what you’re doing. There would be several AOP options as well, but ultimately you’ll still have to decide how to indicate what
Widgetimplementation to use.(Minor nit, you’re not “injecting a singleton”, you’re injecting into a singleton.)