Implement a Logger singleton as a single-element enum (the safest singleton in Java) that keeps a count of messages by level, and use it from two different methods.
Solution
Main.java
import java.util.EnumMap;
import java.util.Map;
enum Level { INFO, WARN, ERROR }
enum Logger {
INSTANCE; // the one and only instance
private final Map<Level, Integer> counts = new EnumMap<>(Level.class);
void log(Level level, String msg) {
counts.merge(level, 1, Integer::sum);
System.out.println("[" + level + "] " + msg);
}
String summary() { return counts.toString(); }
}
public class Main {
static void checkout() {
Logger.INSTANCE.log(Level.INFO, "checkout started");
Logger.INSTANCE.log(Level.WARN, "coupon expired");
}
static void payment() {
Logger log = Logger.INSTANCE; // the same object
log.log(Level.INFO, "payment ok");
log.log(Level.ERROR, "email failed");
}
public static void main(String[] args) {
checkout();
payment();
System.out.println(Logger.INSTANCE.summary());
}
}
Output Verified by compiling and running
[INFO] checkout started
[WARN] coupon expired
[INFO] payment ok
[ERROR] email failed
{INFO=2, WARN=1, ERROR=1}
The JVM guarantees an enum constant is created exactly once, even with serialization or reflection – so an enum is the recommended singleton.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!