php - 善用静态工厂
问题描述
我有一个具有许多依赖项的类。目前这些是在构造函数中设置的:
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());
}
解决方案
推荐阅读
- python - 如何从单独的脚本访问文档字符串?
- blazor - 当 ASPNETCORE_ENVIRONMENT 更改为“开发”以外的任何内容时 - 在 VS 中调试时,Blazor 应用程序看不到来自 razor 类库的资源
- excel - 如何避免“选择”来优化以下代码
- reactjs - 使用多个 HTTP 调用响应 useEffect
- vba - 查找多个条件的 VBA 代码示例
- reactjs - 如何将 WebRTC 视频转换为视频流以解码视频?
- java - 作业图太大,无法提交到 Google Cloud Dataflow
- hibernate - JPA Hibernate 在 IntelliJ 中登录到本地 MySQL 不起作用
- python - Windows 中 asyncio.create_subprocess_exec() 的参数中的引号和空格
- python - numpy:拆分二维 numpy 数组,然后创建二维对角块数组