将服务型对象依赖的对象或参数项,作为其构造函数的参数注入给它

2020-09-21  本文已影响0人  全新的饭

依赖是什么意思?

如果服务型对象A执行自己的任务时,需要让其他服务型对象B执行相应任务。那么称A依赖B。
人话版:如果没有B,A就做不成事,则认为A依赖B。

为什么要将依赖项作为构造函数的参数注入?

为了让依赖于他者的服务型对象实例化后立刻就能被使用。(A必须有B才“能用”)

依赖的都是什么?

  1. 其他对象
  2. 配置值
    可能是储存在某个参数包里的某些参数,可能储存在某个配置文件或其他还储存了其他配置值的大型数据结构中。
    注意注入的应只是服务型对象所需的参数,不要把整个参数包、配置文件(或其他大型数据结构)全部注入。
    不要让对象知道自己没必要知道的东西!
如果需注入多个配置值,最好将它们整合成1个整体(对象)后再注入

例如某服务型对象需要2项配置值:用户名、用户密码。
这两项合起来其实可以看作是用户信息,因此最好能将它们先整合成一个对象(用户信息),再注入该服务型对象。
这样做的好处是将这些配置值的关联关系包含在了表示中,说明了它们不是彼此孤立的值,而是彼此关联的。

// 分别注入用户名和密码
final class ApiClient
{
    private string username;
    private string password;
    
    public function __construct(string username, string password)
    {
        this.username = username;
        this.password = password;
    }
}

// 将用户名和密码整合成一个整体后注入
final class Credentials
{
    private string username;
    private string password;
    
    public function __construct(string username, string password)
    {
        this.username = username;
        this.password = password;
    }
    
    public function username() : string
    {
        return this.username;
    }
    
    public function password() : string
    {
        return this.password;
    }
}

final class ApiClient
{
    private Credentials credentials
    
    public function __construct(Credentials credentials)
    {
        this.credentials = credentials;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读