模块【其他模式】

模块

public class Module {
    /**
     * Module pattern:统一管理功能相关组件的创建、使用和销毁
     */
    @Test
    public void all() throws FileNotFoundException {
        final FileLogModule logModule = FileLogModule.getSingleton();
        logModule.prepare();
        logModule.print("hello");
        logModule.error("error");
        logModule.finish();
    }
}

class FileLogModule{
    private FileLogModule() {
    }
    private static final FileLogModule INSTANCE = new FileLogModule();
    private static final String OUTPUT_FILE = "output.txt";
    private static final String ERROR_FILE = "error.txt";
    private PrintStream output;
    private PrintStream error;

    public static FileLogModule getSingleton() {
        return INSTANCE;
    }

    public void prepare() throws FileNotFoundException {
        output = new PrintStream(new FileOutputStream(OUTPUT_FILE));
        error = new PrintStream(new FileOutputStream(ERROR_FILE));
    }

    public void print(String message) {
        output.println(message);
    }

    public void error(String message) {
        error.println(message);
    }

    public void finish() {
        flushClose(output);
        flushClose(error);
    }

    private void flushClose(PrintStream stream) {
        Optional.ofNullable(stream).ifPresent(s -> {
            s.flush();
            s.close();
        });
    }
}
原文地址:https://www.cnblogs.com/zhuxudong/p/10223814.html