DI和工厂模式之间有什么区别? [英] What's the difference between DI and factory patterns?

查看:66
本文介绍了DI和工厂模式之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个依赖于3个类的类,所有3个类均具有它们依赖的其他类.目前,我正在使用一个容器类来构建所有必需的类,将它们相互注入并返回应用程序.

I have a class which depends on 3 classes, all 3 of which have other classes they rely on. Currently, I'm using a container class to build up all the required classes, inject them into one another and return the application.

容器的简化版本如下所示:

The simplified version of the container looks something like this:

class Builder
{
    private $_options;

    public function __construct($options)
    {
        $this->_options = $options;
    }

    public function build()
    {
         $cache = $this->getCache();
         $response = $this->getResponse();
         $engine = $this->getEngine();

         return new Application($cache,$response,$engine);
    }

    public function getResponse()
    {
         $encoder = $this->getResponseEncoder();
         $cache = $this->getResponseCache();

         return new Response($encoder,$cache);
    }

    // Methods for building each object
}

我不确定这是归类为FactoryMethod还是DI容器.他们似乎都以相同的方式解决了相同的问题-他们建立了对象并注入了依赖关系.该容器具有一些更复杂的构建方法,例如加载观察者并将它们附加到可观察对象上.

I'm not sure if this would be classified as FactoryMethod or a DI Container. They both seem to solve the same problem in the same way - They build objects and inject dependencies. This container has some more complicated building methods, like loading observers and attaching them to observable objects.

工厂应该负责所有的建筑物(加载扩展等),并且DI容器应该使用这些工厂来注入依赖项吗?这样,子包(例如Cache,Response等)可以各自拥有自己的专用工厂.

Should factories be doing all the building (loading extensions etc) and the DI container should use these factories to inject dependencies? That way the sub-packages, like Cache, Response etc, can each have their own specialised factories.

推荐答案

DI容器肯定是工厂,但它是通用工厂.

A DI Container is definitely a Factory, but it's a general-purpose factory.

但是,如果您以一种基于拉动的方式使用它,并要求它每次为您创建依赖项,那么您将使用

However, if you use it in a pull-based way by asking it to create dependencies for you every time you need them, you would be employing the Service Locator anti-pattern. That's just a general-purpose factory and actually has little to do with DI.

真正的依赖注入基于推送的.您可以使用构造函数注入这样的简单模式编写所有代码,并使用DI容器一次在应用程序的

True Dependency Injection is, as the name implies, push based. You write all your code using simple patterns like Constructor Injection, and use the DI Container to resolve your entire dependency graph in one go in the application's Composition Root, injecting all dependencies into their respective consumers.

这篇关于DI和工厂模式之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆