tags:

views:

80

answers:

4

I know this should be simple and I should know it but it's eluding me for the time being.

I am using a singleton pattern to help with logging stuff. However, logging only happens in one class, and the singleton is basically a watcher for a boolean that opens and closes the log file. Because I don't want the file to be opened more than once, or closed more than once, I'm using the singleton pattern. However, I don't want it to be a global value, and I sure as hell don't want other classes, even inside the package accessing it. How can I make it so only this one class use it?

+2  A: 

If you don't want it to be accessed by other classes, why is it a Singleton in the first place? Just make it a private, instanced class and keep a reference to it.

Welbog
A: 

Make the class that logs to the file a singleton class, or make it a variable inside your singleton class. The boolean field should be a private field of your singleton, nobody would be able to access it this way.

Ricardo Villamil
A: 

One - more left field - solution might be to adopt the State pattern in the logger. When the logging flag is set, then the implementation flips to one which opens the file and logs to it. When it is reset, then the implementation flops to one which closes the file and doesn't log. Setting and re-setting isn't a boolean flag any more but a method which does the state-changing.

Graham Lee
+3  A: 

Make it a private class inside the class in which you want to use it. Also, consider making it a static class.

Hemanshu Bhojak
I made it a private inner class
Malfist