Singleton Pattern

Singleton Pattern is used when you only need one instance of a class for an entire program. In most cases, you will provide global access to this singleton instance.

Variables within this instance can be modified from everywhere in the program which is the biggest problem with a singleton object. Serialization and Multithreading are the main two problems to deal with when it comes to singleton and luckily we have a solution which is using Enum.

There are other ways to create a singleton but this is the best and safest way to do it.

How to implement a singleton:
1. Create an Enum class as the singleton class. Enum is thread safe.
2. Make the default constructor private and make no other constructor and by doing this there will be no way for the class to be instantiated using the new keyword.

public enum EnumSingleton {

	INSTANCE;

	private Connection connection = null;

	private EnumSingleton() {
		System.out.println("Get new connection to mysql!");
		try {
			String host = "localhost";
			String port = "3306";
			String dbName = "mysql_playground";

			String username = "root";
			String password = "";

			connection = DriverManager.getConnection(
					"jdbc:mysql://" + host + ":" + port + "/" + dbName
							+ "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC",
					username, password);

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Connection getConnection() {
		return connection;
	}

	// add other logic

}
public class SingletonMain {

	public static void main(String[] args) throws SQLException {
		// best way
		SingletonMain singletonMain = new SingletonMain();

		singletonMain.getUsers();

		// calling this method results in reusing the connection that
		// has been established already. We are using a singleton here.
		singletonMain.getUsers();
	}

	public void getUsers() throws SQLException {
		Connection connection = EnumSingleton.INSTANCE.getConnection();

		Statement stmt = connection.createStatement();

		ResultSet rs = stmt.executeQuery("select * from user");

		while (rs.next()) {

			int id = rs.getInt("id");
			int salary = rs.getInt("salary");

			System.out.println("id: " + id + ", salary: " + salary);
		}
	}
}

Uses

  1. Database connection which creating it with a singleton class can be very useful since it is a heavy task to do.




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.