Every time I have a stateful object with class properties, I resort to using a factory for that class to be used in the dependent class as such:
class Foo
{
Dependency1 d1;
Dependency2 d2;
IdProcessorFactory idProcessorFactory;
public Foo(Dependency1 d1, Dependency2 d2, IdProcessorFactory idProcessorFactory)
{
this.d1 = d1;
this.d2 = d2;
this.idProcessorFactory = idProcessorFactory;
}
private void DoSomething(List<int> ids)
{
foreach(var id in ids)
{
var idProcessor = idProcessorFactory.GetInstance();
idProcessor.Process(id);
}
}
}
I wonder if this is the right approach. Because, since stateful objects are encouraged in an object oriented language, then one has to write a factory for each dependency if multiple instances are to be used in the dependent class. Is this the way to go or is there a better alternative?
(Please note that I am aware of the service locator pattern which is discouraged.)
Aucun commentaire:
Enregistrer un commentaire