I have a class that looks like this
class FileProcessorContext {
private static BufferedWriter fileWriter;
static {
createFile();
}
public static void writeToFile(...) {}
public static synchronized void closeFile(...) {}
}
Can I create FileProcessorContext
as singleton and use it, instead of this pseudo(it keeps some state)-utility class?
You could use a enum with a single enum value as each enum value is out of the box a singleton.
The enum could implement an interface to be testable and in order to be able to switch to another implementation if required :
public enum FileBufferedProcessorService implements FileProcessorService {
SINGLETON;
private BufferedWriter fileWriter;
FileBufferedProcessorService(){
createFile();
}
....
public synchronized void writeToFile(...) {}
public synchronized void closeFile(...) {}
}
And the interface :
public interface FileProcessorService {
void writeToFile(...);
void closeFile(...);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.