【发布时间】:2019-10-15 16:18:34
【问题描述】:
我试图使用log4j2 中的jdbc appender 将信息记录到数据库中。我遇到了这个类来创建连接。
public class ConnectionFactory {
//couldn't understand the logic for need of this interface
private static interface Singleton {
final ConnectionFactory INSTANCE = new ConnectionFactory();
}
private final DataSource dataSource;
private ConnectionFactory() {
//necessary connection creation for DataSource datasource
//connection pooling is used here
}
public static Connection getDatabaseConnection() throws SQLException {
return Singleton.INSTANCE.dataSource.getConnection();
}
}
为了获得连接,我所要做的就是调用getDatabaseConnection() 类。它有效。但我不明白为什么我需要一个名为 Singleton 的接口。如果我不使用它会发生什么。我的意思是,不使用它不仅是删除该代码,而且还相应地进行其他更改,例如必要时使构造函数公开,getDatabaseConnection() 必要时为非静态。
但是,这个名为 Singleton 的接口真的在这里有效吗?我希望我能弄清楚这个逻辑。谢谢。
此代码也可从https://logging.apache.org/log4j/2.x/manual/appenders.html#JDBCAppender获得
【问题讨论】:
-
你是问为什么 ConnectionFactory 是单例,还是说为什么单例是使用嵌套接口实现的?
-
@shmosel 我不了解 OP,但我很想知道为什么使用这样的嵌套接口来实现它。你能指出我正确的方向吗?
-
@Voldemort en.wikipedia.org/wiki/…