1

i have a object in my application which is needed at several points. That means, there are a lot of objects, which holds a reference to this object. Is there an easy way, to spread this reference to all the other objects? One possibility might be to use a singleton. Another way is to use dependency injection. Are these ideas good practice or is there a better way to do this?

Thanks!

Aeon
  • 87
  • 1
  • 11

2 Answers2

2

Since you need to share the same object with all the other objects, making it Singleton is a good choice. (If that object is the only instance of its class. Otherwise, you could implement a similar thing, but it wouldn't be technically correct to call it Singleton.)

Dependency injection makes your code independent of the specific object's class and construction procedure. If you have multiple classes that may be used in different situations, then dependency injection will help. The singleton pattern itself can be a way of injecting dependency if the return type of your getInstance() method is an interface. You don't necessarily have to use a dependency injection framework for that.

emjay
  • 420
  • 1
  • 5
  • 16
1

If there is only one instance to be referenced, use Singleton, you may choose Eager initialization or Lazy Initialization according to your need.

Or if you have many instance rather than only one, use object pooling

Community
  • 1
  • 1
JaskeyLam
  • 15,405
  • 21
  • 114
  • 149