What is the difference between singleton and dependency injection

is the dependency injection design pattern or respect the design pattern singleton ?

Dependency Injection involves passing a service to an object; typically you pass an interface. The purpose of this is that the object being injected doesn’t need to create an instance of the class and makes it easier for code reuse and testing.

The Singleton design pattern ensures an object only has once instance and cannot be re-instantiated.

For Dependency Injection, typically you would create an instance of the service outside of the target object (the client) and pass it to the client.

For a Singleton, the object instantiates itself only once and you can only get/set properties or use methods of the object; you cannot create a new singleton object.

2 Likes

Just adding more information: there are also a decent number of Dependency Injection (DI) frameworks that support the singleton pattern through DI. Typically these work by having a large mapping of providers for a given key. For a singleton object, it returns the exact same instance when that key is requested (similar to how the getInstance() method works in the singleton pattern). For other objects, it can construct the appropriate object for the given key using a configurable method (or perhaps using a default constructor).

In Java, you might look into Guice or Dagger if you want to see particular frameworks for DI.

2 Likes