0

我有一个具有许多依赖项的类。目前这些是在构造函数中设置的:

class Thing
{
    public function __construct()
    {
        $this->dependencyA = new DependencyA();
        $this->dependencyB = new DependencyB();
        $this->dependencyC = new DependencyC($this);
        $this->dependencyD = new DependencyD($this);
    }        
}

这在 IoC 和 DI 方面设计得很糟糕,所以我想重新设计它,以便我的依赖项存在于构造函数中。

public class Thing
{
    public function __construct(
        $dependencyA, $dependencyB, $dependencyC, $dependencyD)
    {
        $this->dependencyA = $dependencyA;
        $this->dependencyB = $dependencyB;
        $this->dependencyC = $dependencyC;
        $this->dependencyC->setThing($this);
        $this->dependencyD = $dependencyD;
        $this->dependencyD->setThing($this);
     }
}

这使测试变得更容易,但是我不希望客户端必须实例化所有依赖项。它们是Thing. 这会是下面提议的静态工厂的一个很好的候选者吗?然而,这确实改变了需要Thing作为依赖项的依赖项的实例化方式(即,我必须通过 setter 而不是构造函数设置依赖项),这让我有点不舒服。我提出的解决方案如下。有更好的方法吗?

private class Thing
{
    public function __construct(
        $dependencyA, $dependencyB, $dependencyC, $dependencyD)
    {
        $this->dependencyA = $dependencyA;
        $this->dependencyB = $dependencyB;
        $this->dependencyC = $dependencyC;
        $this->setThing($this);
        $this->dependencyD = $dependencyD;
        $this->setThing($this);
    }

    public static function createThing()
    {
        return new Thing(
            new DependencyA(),
            new DependencyB(),
            new DependencyC(),
            new DependencyD());
}
4

0 回答 0