How to change the state of a singleton in runtime

Posted by user34401 on Programmers See other posts from Programmers or by user34401
Published on 2014-08-19T07:10:25Z Indexed on 2014/08/19 10:30 UTC
Read the original article Hit count: 224

Consider I am going to write a simple file based logger AppLogger to be used in my apps, ideally it should be a singleton so I can call it via

public class AppLogger {
    public static String file = "..";

    public void logToFile() {
        // Write to file
    }

    public static log(String s) {
        AppLogger.getInstance().logToFile(s);
    }
}

And to use it

AppLogger::log("This is a log statement");

The problem is, what is the best time I should provide the value of file since it is a just a singleton?

Or how to refactor the above code (or skip using singleton) so I can customize the log file path? (Assume I don't need to write to multiple at the same time)

p.s. I know I can use library e.g. log4j, but consider it is just a design question, how to refactor the code above?

© Programmers or respective owner

Related posts about java

Related posts about design-patterns