mercredi 28 août 2019

how can i implement singleton pattern on this project, to get the data base connection?

I have this example of Singleton pattern implementation :

public class Singleton {
    //singleInstance
    private static Singleton unicaInstancia = new Singleton();

    //nadie puede crear mi clase con el constructor en privado/
    private Singleton(){
        System.out.println("no one can create my class"
                + " with the builder/constructor in private");
    }
    //punto de acceso global
    //global access point
    public static Singleton getInstance(){
        return unicaInstancia;
    }



}
 //clase de prueba/ TestClass
class test{
    public static void main(String[] args){
        Singleton sgtn1 = Singleton.getInstance();
        Singleton sgtn2 = Singleton.getInstance();
        print("s1", sgtn1);
        print("s2", sgtn2);
    }

    static void print(String name, Singleton object){
        System.out.println(String.format("Object : %s, Hashcode: %d",name,object.hashCode()));
    }
}

this is my project structure :

enter image description here

this is the class I want to get single instance:

public class UConnection {

    private static Connection con = null;


   public static Connection getConnection(){
        try{
            if(con == null){
                Runtime.getRuntime().addShutdownHook(new MiShDwnHook());
                ResourceBundle rb = ResourceBundle.getBundle("backEnd.jdbc");
                String driver = rb.getString("driver");
                String url = rb.getString("url");
                String pwd = rb.getString("pwd");
                String usr = rb.getString("usr");

                Class.forName(driver);
                con = DriverManager.getConnection(url, usr, pwd);
            }
            return con;
        }catch(Exception ex){
            ex.printStackTrace();
            throw new RuntimeException("Error al crear la conexion", ex);
        }
    }
}

class MiShDwnHook extends Thread {

    public MiShDwnHook() {
    }

    @Override
    public void run(){
        try{
            Connection con = UConnection.getConnection();
            con.close();
        }catch(Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }
}

then my question is how can I do to get a single instance of my connection to the database in the backEnd package and as I can check it, I would like to know if someone can answer this question, previously I thought of coding everything in the builder but that doesn't look good to me, that's the only way to implement the singleton and make it work ? , I need help please, thank you

Aucun commentaire:

Enregistrer un commentaire