Win a copy of OCP Oracle Certified Professional Java SE 11 Developer Practice Tests this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
Sheriffs:
  • Devaka Cooray
  • paul wheaton
  • Mark Herschberg
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Frits Walraven
  • Jj Roberts
Bartenders:
  • Carey Brown
  • salvin francis
  • Piet Souris

Dependency injection vs Singleton pattern

 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ranchers,

Nowadays, i am coming across many instances where people/developers are willing to use dependency injection rather than singleton classes/patterns?Can the dependency injection be really used in all the places/situations where a singleton class is needed?
Need your thoughts/suggestions on this.

Cheers
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The Singleton pattern is mostly considered an *anti*-pattern now. Static creation makes it difficult to test and, if suddenly the class doesn't need to be a singleton anymore, requires lots of changes, because you have to change how all the users of the class get the reference.

Dependency injection can create singleton objects in an application through only configuration. The DI container handles the creation of classes and passing references to users of the class around - so the class doesn't need to define static creation methods; and users of the class don't have to know it's a singleton to get a reference, it's reference is just passed to the class like any other dependency.

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Adding to what Nathan said, leaving the object creation strategy to a Dependency injection container makes it easy to inject mock version of the dependencies and test the class under isolation.
Nevertheless, the DI framework can be instructed to maintain a single instance of the class...
 
reply
    Bookmark Topic Watch Topic
  • New Topic