theJava
theJava

Reputation: 15044

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. Now, I do the instantiation part in my onClick Method.

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?

Upvotes: 1

Views: 134

Answers (1)

RNJ
RNJ

Reputation: 15572

If you are asking about injecting Apple into AppleAsynTask then what you have done is correct. Dependency Injection is a type of Inversion of Control. There are other ways you could instantiate the Apple outside of this program. 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.

Upvotes: 1

Related Questions