I read a template in Factory and came across articles suggesting using a Factory template in conjunction with dependency injection to maximize reuse and testability. Although I could not find concrete examples of this Factory -DI hybrid, I will try to give some examples of my interpretation code. However, my question is how this approach improves testability.
My interpretation:
So we have a class Widget:
public class Widget {
}
And we want to enable s WidgetFactoryto control the construct Widget:
public interface WidgetFactory {
public abstract static Widget getWidget();
}
public class StandardWidgetFactory implements WidgetFactory {
@Override
public final static Widget getWidget() {
}
}
public class TestWidgetFactory implements WidgetFactory {
@Override
public final static Widget getWidget() {
}
}
Spring DI ( API, ), , Guice - IoC; , WidgetFactory , . Spring config beans :
<bean id="widget-factory" class="org.me.myproject.StandardWidgetFactory"/>
<bean id="test-widget-factory" class="org.me.myproject.TestWidgetFactory"/>
<bean id="injected-factory" ref="${valueWillBeStdOrTestDependingOnEnvProp}"/>
:
WidgetFactory wf = applicationContext.getBean("injected-factory");
Widget w = wf.getWidget();
, ( ), , .properties, , Spring DI StandardWidgetFactory <<29 > .
?!?. , Widget. , , .
:
, , , , , Widget. , - :
public class Fizz {
public void doSomething() {
WidgetFactory wf = applicationContext.getBean("injected-factory");
Widget widget = wf.getWidget();
int foo = widget.calculatePremable(this.rippleFactor);
doSomethingElse(foo);
}
}
, , "mock Widgets" unit test Fizz::doSomething().
, : , , ( ). , .
, : ( ), , , Factories ?!?
way-overengineering! ? , , Factory, ?! . .