singleton or class with static field

时间:2017-06-15 09:48:38

标签: java

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?

1 个答案:

答案 0 :(得分:1)

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(...);

}