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;
}
}
The constructor has to be private in order to ensure the class is a singleton, whether or not you create a single instance of it. If no private constructor were declared, Java would automatically provide a public no-arg constructor for it.
The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching, and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade, etc.
A singleton cannot be made without a private constructor! If a class has a public constructor, then anybody can create an instance of it at any time, that would make it not a singleton. In order for it to be a singleton there can only be one instance.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
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.
If there no such a private constructor, Java will provide a default public one for you. Then you are able to call this constructor multiple times to create several instances. Then it is not a singleton class any more.
If you don't need lazy initiation:
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
is the best way, because is thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With