0

I got 3 classes, A,B and C.

Only 1 instance of class A exits at any given time but hundreds of objects of class B and C will exist.

Class A calls a method of class B. Class B calls a method of class C. And class C eventually calls a method of the class A object.

What would be the best and cleanest way to provide the reference to the class A object in C?

  1. Saving it in a private variable and initializing it via the constructor?
  2. Creating a static getInstance() method in Class A which returns the object itself?
  3. Or passing "this" through parameters from A to B to C?

Any C Object will call the method of A multiple time in his lifetime.

user3394605
  • 77
  • 1
  • 2
  • 7

3 Answers3

0

I would suggest create a static getInstance() method in Class A which returns the object itself.

0

Option 2. Have your Singleton class contain the instance privately with a private constructor and return the instance using get instance. This the commonly used pattern.

Option 1 makes the constructor open to other methods which is not needed since it should only be called once (if I'm reading the option correctly). Option 3 will clutter your code.

Jias
  • 164
  • 12
0

The most convenient way is certainly #2. The "cleanest" is probably #1, or #3, depending on the circumstances.

The Singleton (#2) pattern has some problems. That does not mean you should avoid it at all costs. But you should be aware of the implications.

For some information on the topic see What is so bad about singletons?

Community
  • 1
  • 1
Thomas Stets
  • 2,917
  • 4
  • 13
  • 28