当前位置: 动力学知识库 > 问答 > 编程问答 >

java - What mainly differs Dependency Injection from Factory Design pattern?

问题描述:

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

网友答案:

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
网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: