Last active
December 19, 2021 10:20
-
-
Save sunmeat/522246ba43c82da17cfc to your computer and use it in GitHub Desktop.
singleton example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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