Can you briefly explain: What mainly differs Dependency Injection from Factory Design pattern?
Additionally: Is 开发者_如何学Cit 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.
精彩评论