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

查看:276
本文介绍了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天全站免登陆