Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active December 19, 2021 10:20
Show Gist options
  • Save sunmeat/522246ba43c82da17cfc to your computer and use it in GitHub Desktop.
Save sunmeat/522246ba43c82da17cfc to your computer and use it in GitHub Desktop.
singleton example
package com.alex.static;
class LoggerSingleton {
private static LoggerSingleton instance = null;
private int logCount = 0;
private LoggerSingleton() {
// nothing to do here :)
}
public static LoggerSingleton getInstance() {
return instance == null ? instance = new LoggerSingleton() : instance;
}
public void log(String message) {
System.out.println(logCount + ": " + message);
logCount++;
}
}
class SingletonDemo {
public static void run() {
doHardWork();
}
public static void doHardWork() {
LoggerSingleton logger = LoggerSingleton.getInstance();
HardProcessor processor = new HardProcessor(1);
logger.log("Hard work started..."); // пишем в лог!
processor.processTo(5);
logger.log("Hard work finished!");
}
}
class HardProcessor {
private int start;
public HardProcessor(int start) {
this.start = start;
LoggerSingleton.getInstance().log("Processor just created."); // пишем в лог!
}
public int processTo(int end) {
int sum = 0;
for (int i = start; i <= end; ++i) {
sum += i;
LoggerSingleton.getInstance().log("In progress..." + i);
}
LoggerSingleton.getInstance().log("Processor just calculated some value: " + sum);
return sum;
}
}
class Program {
public static void main(String[] args) {
SingletonDemo.run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment