单例是1994年由四人帮(Gang of Four)发布的一种创建型设计模式。
由于其简单的实现方式,我们倾向于过度使用它。因此,现在它被认为是一种反模式。在将单例模式引入我们的代码之前,我们应该自问是否真的需要它提供的功能。
在本教程中,我们将讨论单例设计模式的一般缺点,并看看我们可以使用的替代方案。
2. 代码示例
首先,让我们创建一个我们将在示例中使用的类:
public class Logger {
private static Logger instance;
private PrintWriter fileWriter;
public static Logger getInstance() {
if (instance == null) {
instance = new Logger();
}
return instance;
}
private Logger() {
try {
fileWriter = new PrintWriter(new FileWriter("app.log", true));
} catch (IOException e) {
e.printStackTrace();
}
}
public void log(String message) {
String log = String.format("[%s]- %s", LocalDateTime.now(), message);
fileWriter.println(log);
fileWriter.flush();
}
}
大约 6 分钟