Singleton Design Pattern Implementation with Database SQL and Java
1 Problem
when You have a Resource and you want to be sure the whole program use this resource in every part in the program to ensure the synchronization of data or you want to save the resource and time waste by creating multiple object of this resource like database or config files or logging file in systems.
2 solution
Now we have to use singleton design pattern to solve this problem by making one instance and make sure that the whole program have access to this instance and use it
3 Is i have singleton design
to say i have a singleton design pattern you must have a one instance of the resource and each part of code can take and use it when want to connect with the resource and no one can make another instance of this class .
4 Implementation
To implement this
Get Mohamed Othman’s stories in your inbox
Join Medium for free to get updates from this writer.
a. we have to make the constructor private to prevent any one make a new object of the class .
b. make the resource in a Static Variable and private to make it part of class not object.
c. make static method return the resource
now if you followed up this steps you have implement the Design pattern.
5 simple code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String PASSWORD = "P@ssw0rd";
private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=Testdb;encrypt=false";
private static final String USERNAME = "sa";
private static Connection instance = null;
private DatabaseConnection(){}
public synchronized static Connection getinstance(){
if(instance != null) return instance ;
try {
instance = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return instance ;
}
}we add synchronized keyword in function to ensure no two threads access the instance in the same time before Initialization it and make two object.






