Sometimes when I design my classes, I need some dependency classes with similar constructor parameters. Assume we have
interface IDependency {
void DoSomething();
}
class DependencyClass : IDependency {
public DependencyClass(int length) {...}
...
}
class MainClass {
public MainClass(int length, IDependency dependency) {...}
...
}
MainClass needs an instance of DependencyClass with the same length. I have two methods in mind to deal with it:
-
Not creating instances of
MainClassdirectly and always getting them from a factory. This way I can make sure that the desiredIDependencyinstance will be provided toMainClassconstructor. -
Passing a factory interface, say
IDependencyFactory, toMainClassconstructor instead ofIDependency. So that I can get the desired instance ofDependencyClasswithin myMainClassimplementation.
I'm not sure if either of them is a good choice. Is there a best practice in this case?
Aucun commentaire:
Enregistrer un commentaire