假设我有一个类,其中有一些方法依赖于另一个对象来执行它们的职责。不同之处在于它们都依赖于同一类对象,但需要该类的不同实例。或者更具体地说,每个方法都需要一个干净的类实例,因为这些方法将修改依赖项的状态。
这是我想到的一个简单示例。
class Dependency {
public $Property;
}
class Something {
public function doSomething() {
// Do stuff
$dep = new Dependency();
$dep->Property = 'blah';
}
public function doSomethingElse() {
// Do different stuff
$dep = new Dependency();
$dep->Property = 'blah blah';
}
}
技术上我可以做到这一点。
class Something {
public function doSomething(Dependency $dep = null) {
$dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
$dep->Property = 'blah';
}
public function doSomethingElse(Dependency $dep = null) {
$dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
$dep->Property = 'blah blah';
}
}
我的问题是我必须经常检查传入的依赖对象是否处于正确状态。新创建的状态。所以我只想做这样的事情。
class Something {
protected $DepObj;
public function __construct(Dependency $dep) {
$this->DepObj = $dep && is_null($dep->Property) ? $dep : new Dependency();
}
public function doSomething() {
// Do stuff
$dep = clone $this->DepObj;
$dep->Property = 'blah';
}
public function doSomethingElse() {
// Do different stuff
$dep = clone $this->DepObj;
$dep->Property = 'blah blah';
}
}
这使我能够获得处于正确状态的对象的一个实例,如果我需要另一个实例,我可以直接复制它。我只是好奇这是否有意义,或者我是否忽略了关于依赖注入(inject)和保持代码可测试的基本指南。
最佳答案
我会为此使用工厂模式:
class Dependency {
public $Property;
}
class DependencyFactory
{
public function create() { return new Dependency; }
}
class Something {
protected $dependencies;
public function __construct(DependencyFactory $factory) {
$this->dependencies = $factory;
}
public function doSomething() {
// Do different stuff
$dep = $this->dependencies->create();
$dep->Property = 'Blah';
}
public function doSomethingElse() {
// Do different stuff
$dep = $this->dependencies->create();
$dep->Property = 'blah blah';
}
}
您可以通过引入接口(interface)进一步解耦工厂:
interface DependencyFactoryInterface
{
public function create();
}
class DependencyFactory implements DependencyFactoryInterface
{
// ...
}
class Something {
public function __construct(DependencyFactoryInterface $factory)
...
关于php - 克隆依赖项的副本(依赖注入(inject))是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17847758/