简体   繁体   English

谁能帮我依赖注入?

[英]Can anyone help me out in dependency Injection?

public class Apple {  
    private final Orange orange;  
    private final Pear pear;  
    private final Banana banana;  

    public Apple(Orange orange, Pear pear, Banana banana) {  
        this.orange = orange;  
        this.pear = pear;  
        this.banana = banana;  
    }  

    // methods  
}

This is my POJO class. 这是我的POJO课。 Now, I do the instantiation part in my onClick Method. 现在,我在onClick方法中执行实例化部分。

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Apple apple = new Apple(myOrange, aPear, theBanana);   
        new AppleAsyncTask(apple ).execute();
    })
};

How can I avoid this instantiation part and do something better using Dependency Injection? 如何避免这个实例化部分,并使用依赖注入来做得更好? Or is what I'm doing right? 还是我在做的对吗?

If you are asking about injecting Apple into AppleAsynTask then what you have done is correct. 如果您询问有关将Apple注入AppleAsynTask的问题,那么您所做的是正确的。 Dependency Injection is a type of Inversion of Control . 依赖注入是控制反转的一种 There are other ways you could instantiate the Apple outside of this program. 您还可以通过其他方法在该程序之外实例化Apple。 For example you could use a factory or a service locator 例如,您可以使用工厂服务定位器

button.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      new AppleAsyncTask(AppleFactory.getApple(myOrange, aPear, theBanana)).execute();
  })
};

What you are doing looks good to me. 你在做什么对我来说很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM