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
MainClass
directly and always getting them from a factory. This way I can make sure that the desiredIDependency
instance will be provided toMainClass
constructor. -
Passing a factory interface, say
IDependencyFactory
, toMainClass
constructor instead ofIDependency
. So that I can get the desired instance ofDependencyClass
within myMainClass
implementation.
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