为什么在Singleton类中有私有构造函数是必须的 [英] Why is it mandatory to have private Constructor inside a Singleton class
问题描述
这是我获得数据库连接的单例类。
This is my singleton class for obtaining the database connection.
我在这里有一个问题:为什么强制在单例类中有私有构造函数我的整个应用程序我只调用这个类一次),并且作为一个类的一个实例可以使用静态方法来实现?
I have a question here: why it compulsory to have a private constructor inside a singleton class (as throughout my entire application I am calling this class only once) and as one instance of a class can be achieved using the static method?
可以避免这个私有构造函数,它是mantadatory?
Can this private constructor can be avoided, or is it mantadatory?
public class ConnPoolFactory {
private static DataSource dataSource;
private static Connection connection;
private ConnPoolFactory() {
System.out.println(" ConnPoolFactory cons is called ");
}
public static synchronized Connection getConnection() throws SQLException {
try {
if (connection == null) {
Context initContext = new InitialContext();
Context envContext = (Context) initContext
.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/Naresh");
connection = dataSource.getConnection();
} else {
return connection;
}
} catch (NamingException e) {
e.printStackTrace();
}
return connection;
}
}
推荐答案
否则,每个人都可以创建一个类的实例,所以它不再是单例。根据定义,单身人士只能存在一个实例。
Otherwise everyone can create an instance of your class, so it's not a singleton any more. For a singleton by definition there can exist only one instance.
这篇关于为什么在Singleton类中有私有构造函数是必须的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!