对于依赖注入,我知道我必须将一个类的实例传递给主实例,而不是主类创建它自己的实例,就像这样(php):
class Class_One {
protected $_other;
public function setOtherClass( An_Interface $other_class ) {
$this->_other_class = $other_class;
}
public function doWhateverYouHaveToDoWithTheOtherClass() {
$this->_other_class->doYourThing();
}
}
interface An_Interface {
public function doYourThing();
}
class Class_Two implements An_Interface {
public function doYourThing() { }
}
class Class_Three implements An_Interface {
public function doYourThing() { }
}
// Implementation:
$class_one = new Class_One();
$class_two = new Class_Two();
$class_three = new Class_Three();
$class_one->setOtherClass( $class_two );
$class_one->doWhateverYouHaveToDoWithTheOtherClass();
$class_one->setOtherClass( $class_three );
$class_one->doWhateverYouHaveToDoWithTheOtherClass();
这一切都很好。我知道由于 Class_Two 和 Class_Three 都实现了 An_Interface,因此它们可以在 Class_One 中互换使用。Class_One 不会知道它们之间的区别。
我的问题是,不是将实例传递给 setOtherClass,而是传递一个诸如“Class_Two”之类的字符串,并让 Class_One 的 setOtherClass 方法像这样实际创建实例本身,这是否是一个好主意:
class Class_One {
...
public function setOtherClass( $other_class_name ) {
$this->_other_class = new $other_class_name();
}
...
}
这种破坏依赖注入的目的,还是完全有效?我认为这种类型的设置可以帮助我进行配置,用户可以在前面指定他想在字符串中使用哪个类,然后可以将其传递给 Class_One..
实际上,写出来让我觉得这可能不是一个好的解决方案,但我仍然会发布这个,以防有人能给我一些关于为什么我应该/不应该这样做的好的反馈。
谢谢 =)
瑞安