[英]singleton or class with static field
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? 我可以将
FileProcessorContext
创建为单例并使用它,而不是使用此伪(具有某些状态)实用程序类吗?
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(...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.