简体   繁体   中英

Creating a Generic Object Factory

While developing an application i am struck in a case where not clear how should i proceed.My Application is not a very big implimentation so don't want to add any DI container (Spring/ Guice).

I have my Controler layer from where i need to call my service layer and i have two ways to create an instance of ServiceObject.

  1. use simple new operator.
  2. Create a factory layer.

i am aware about the factory pattern, but my intention is to create a generic ObjectFactory which should be capable enough to create and inject the given object.

Something similar to what Spring does (not that much) like exposing some setter method in my controller class and let that factory inject the specified object in that.

Any starting pointer in this regard will be helpful

Thanks in advance

Just use Spring or Guice, whichever you're more familiar with. They're both really quite lightweight, and other people will be able to understand your application more easily than if you roll you own dependency injection. Your own implementation will eventually end up looking like one of them, but with less functionality and more bugs.

My Application is not a very big implimentation so don't want to add any DI container (Spring/ Guice)

I think your applications size is not something you should not take into account (provided it's really not a HelloWolrd :)). As artbristol said the point in using an already existing framework is that you won't make the mistakes in your own implementation that others already did and solved later. I don't know if you have practical Spring knowledge (but we already know you are familiar with the concept behind very well) so i advise you to have a look at some of the basic tutorials on the topic and you will see how easy you can start using Spring.

http://www.vogella.de/articles/SpringDependencyInjection/article.html

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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