Bonjour,

Je reviens vers vous pour utiliser un singleton. (J'en comprends l''utiliter)

Mais c'est le mécanisme qui est pour moi encore un peu abscon !


J'ai trouvé pleins de tutoriels sur Developpez et sdz

Mais je suis toujours dans l'incompréhension de comment l'appeler

J'ai créé un projet test sous Netbeans avec deux classe
- 1er main.java
- 2e singleton.java

Exemple du singleton:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author stefan
 */
public class Singleton {
    private String name = "";
    private static String url = "jdbc:sqlite:test.db";
 
    private static Connection connect;
 
/**
 
        /**
         * Constructeur privé
         */
	private Singleton(){
		try {
			connect = DriverManager.getConnection(url);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
 
	/**
         * Méthode qui va nous retourner notre instance
         * et la créer si elle n'existe pas...
         * @return
         */
	public static Connection getInstance(){
		if(connect == null){
			new Singleton();
		}
		return connect;	
	}	
 
    }
Et dans mon main :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
import java.sql.Connection;
 
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 *
 * @author stefan
 */
public class main {
 
    public static void main(String[] args) {
        try {
			Statement rs = Connection.getInstance().prepareStatement("SELECT * FROM mytable");
 
            //Affichage des résultats
 
            while (rs.next()) {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                System.out.println("Id = " + id + ", nom = " + name);
            }
 
            //Fermeture de la connexion à la base
 
 
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
}
et j'ai une une erreur au niveau du getInstance() ?

je suis un peu perdu. si vous pouviez me remettre sur les rails


Merci