为什么在单例类中必须有私有构造函数 [英] 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?
这个私有构造函数可以避免吗,还是必须的?
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.
这篇关于为什么在单例类中必须有私有构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文