0

I know the simple differences between them, but when it come to the scenario where I want to share an object instance in the app, I can done this by using DI or Singleton.

when this question come to my mind I became confused, since I can use both, I think that one of them must be better than the other in cases like multi-threading or memory management JVM or code maintainability ...

can someone tell me what is the advantages and disadvantages of using one of them over the other in the above scenario and what is the correct choice ?

piet.t
  • 11,718
  • 21
  • 43
  • 52
Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42
  • 2
    This question is going to get a lot of opinionated answers since both approaches "work". Many (myself included) consider the Singleton to be an anti-pattern, and should be avoided unless absolutely necessary. Check this SO question (https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) for some reasons why singletons should be avoided. I'd always go for DI over Singletons as it promotes good design. – wesrobin Jun 27 '18 at 08:23
  • I'm not so sure this is a question of 'or'. You can still inject a singleton (http://simpleinjector.readthedocs.io/en/latest/lifetimes.html#singleton). I think it's important to be clear that the singleton pattern is more about an instance's lifetime than how a dependent type gets a reference to it. – David Osborne Jun 27 '18 at 10:09

2 Answers2

1

Singleton in the design pattern that states only one instance per jvm can be created (if implemented correctly).

DI(Dependency injection) is the design pattern that takes responsibility injecting dependency(inversion of control). Dependency can be singleton/prototype/scoped ... etc. Other than injecting dependency, DI patterns like spring DI also controlls lifecycle of bean.

Mradul Pandey
  • 2,034
  • 1
  • 14
  • 12
1

Firstly, Both DI and Singleton are Design-patterns.

Dependency injection: DI is a way of injecting dependent objects into your application.

Singleton pattern: Create one and only instance of an object. Source:Design patterns-Singleton

can someone tell me what is the advantages and disadvantages of using one of them over the other in the above scenario and what is the correct choose ??

DI takes care of object creation, configuration and injection. That means DI can create, configure and inject a Singleton object too. DI is helpful when you want to make object creation externalised, loosely coupled and easily maintainable.

Singleton provides only one instance of the object and where you can access the object globally. This object can be injected into the application by DI also. This is helpful when you want only one object, lazy initialisation (creation on first use) and global access are needed.