2

Can you briefly explain: What mainly differs Dependency Injection from Factory Design pattern?

Additionally: Is it possible to demonstrate the difference very simply by a code example?

Thanks

2
  • Dependency injection semantics varies with each framework and cannot easily be demonstrated, although it's basically code which you define to do instantiation for you. Factory pattern code samples are easily found using a search engine. Further, many DI frameworks relies heavily on creational patterns such as the Factory pattern. Commented Sep 13, 2011 at 20:43
  • possible duplicate of What's the difference between DI and factory patterns? Commented Sep 14, 2011 at 7:12

3 Answers 3

2

With Factory (or any other Creation pattern), the caller has to know how to get the object and has to "explicitly" ask for it before consuming it.

Car car = CarFactory.getCarByModel(LUXURY);

Whereas when using DI, the responsibility to pass the desired object is delegated to some external (container mostly) entity which knows how to create the object (by reading the config already defined) and make it available to the caller silently.

Car car = getCar();
void setCar(Car car){..} // container sets the car fromoutside
Sign up to request clarification or add additional context in comments.

Comments

2

The factory pattern is typically useful to repeatedly create instances of an object with possibly complex instantiation logic. This way, your classes knows of the factory and requests instances.

Dependency injection goes one step further to completely abstract away instantiation logic as far as your classes are concerned. All your code needs to care about is to declare the dependencies they need, without bothering where they come from.

For a nice in-depth guide, see Inversion of Control Containers and the Dependency Injection pattern.

Comments

1

Same goals are achieved with both patterns, it's just that with the factory design pattern you have to write code whereas with DI you use an existing DI framework to do the job for you and simply do the configuration of the dependencies. With the factory pattern you have to write factories for you classes.

1 Comment

Dependency injection is a way of designing classes and does not require a container. Containers just happen to be one convenient way of handling building the object graph.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.