Vaandu
Vaandu

Reputation: 4935

Using singleton class instance as class level variable is acceptable?

I have a singleton class. MsgLog

Can I use this class like below? Is there anything wrong with this?

public class SomeBean {
   MsgLog log = MsgLog.getInstance(); // IS THIS FINE?

   // some code
   private void someMethod() {
        log.printIt(" test ");
   }
}

Upvotes: 1

Views: 322

Answers (2)

Alan Stokes
Alan Stokes

Reputation: 18964

Yes, that's fine. You should probably make it private static final though.

In general there are issues with singletons; it's better for a class to accept the things it depends on as constructor parameters than for the class to depend on singletons.

But lots of code treats logging specially, for better or worse.

Upvotes: 1

Kevin Sheehan
Kevin Sheehan

Reputation: 418

Yes this is perfectly acceptable and most would argue that this is the proper way of using a Logger class. Here is another stack overflow answer that explains it a little better:

https://stackoverflow.com/a/4085524/2016771

Upvotes: 1

Related Questions