-1

I am new to design patterns. I want to use the singleton design pattern for this database class. Can anyone help me with this?

Here is my complete code:

public interface ResourceConnection {
    public Connection getConnection();
}

public class ResourceConnectionFactory {
    public ResourceConnection getConnection() {
        return new MysqlResourceConnectionImpl();
    }
}


public class MysqlResourceConnectionImpl implements ResourceConnection {

    Connection con = null;

    @Override
    public Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "root");
        } 
        catch (ClassNotFoundException ex) {
            Logger.getLogger(MysqlResourceConnectionImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(MysqlResourceConnectionImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }
}
Arnaud
  • 7,259
  • 10
  • 50
  • 71
Buddhika Nelum
  • 33
  • 1
  • 12
  • what makes you think that for a "Database class" as you call it, the way to make it a singleton is any different compared to for other classes? – Stultuske Jun 07 '18 at 06:20
  • Check this link https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples – Stultuske Jun 07 '18 at 06:21

2 Answers2

0

To make any class singleton you have to insure following things. (Singleton design pattern can be applied anywhere. There is no different implementation for database class)

  1. Private constructor to restrict instantiation of class
  2. Private static variable of the same class which will store the only instance of the class.
  3. Public method to get this instance of class. This is the access point for other classes.

You can use this link from Java Singleton Design Pattern. All the credit to this url.

Abhijeet
  • 4,069
  • 1
  • 22
  • 38
0

I understand what you are doing is that getting a single connection for a application.If you are re-using that connection in multiple places it will become error prone. Instead of doing that you can use Connection Pool to set up the connection for you. Here is an example for Connection Pool using DBCP

mano_ksp
  • 131
  • 1
  • 12