什么是控制反转? [英] What is Inversion of Control?

查看:125
本文介绍了什么是控制反转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 这是什么?

  2. 解决了哪些问题?

  3. 什么时候适用,何时不适用?


解决方案

控制反转(IoC)和依赖注入(DI)模式都是从代码中删除依赖关系。



例如,说你的应用程序有一个文本编辑器组件,你想提供拼写检查。你的标准代码看起来像这样:

  public class TextEditor 
{
private SpellChecker checker;
public TextEditor()
{
this.checker = new SpellChecker();
}
}

我们在这里做的是创建一个TextEditor和SpellChecker。
在IoC情况下,我们改为执行以下操作:

  public class TextEditor 
{
private IocSpellChecker checker;
public TextEditor(IocSpellChecker checker)
{
this.checker = checker;
}
}

在第一个代码示例中,我们将实例化SpellChecker( this.checker = new SpellChecker(); ),这意味着TextEditor类直接依赖于SpellChecker类。



在第二个代码示例中,我们通过在TextEditor构造函数签名中拥有SpellChecker依赖关系类(不初始化类中的依赖关系)来创建抽象。这允许我们调用依赖关系,然后将它传递给TextEditor类,如下所示:

  SpellChecker sc = new SpellChecker; // dependency 
TextEditor textEditor = new TextEditor(sc);

现在,创建TextEditor类的客户端可以控制使用哪个SpellChecker实现。我们正在将依赖关系注入到TextEditor签名中。



这只是一个简单的例子,一系列文章,由Simone Busoli更详细地解释。


Inversion of Control (or IoC) can be quite confusing when it is first encountered.

  1. What is it?
  2. What problems does it solve?
  3. When is it appropriate and when not?

解决方案

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:

public class TextEditor
{
    private SpellChecker checker;
    public TextEditor()
    {
        this.checker = new SpellChecker();
    }
}

What we've done here creates a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:

public class TextEditor
{
    private IocSpellChecker checker;
    public TextEditor(IocSpellChecker checker)
    {
        this.checker = checker;
    }
}

In the first code example we are instantiating SpellChecker (this.checker = new SpellChecker();), which means the TextEditor class directly depends on the SpellChecker class.

In the second code example we are creating an abstraction by having the the SpellChecker dependency class in TextEditor constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:

SpellChecker sc = new SpellChecker; // dependency
TextEditor textEditor = new TextEditor(sc);

Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the the dependency to the TextEditor signature.

This is just a simple example, there's a good series of articles by Simone Busoli that explains it in greater detail.

这篇关于什么是控制反转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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