Factory Method + Singleton
package br.com.caelum.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @função Fornecer uma Única Fábrica de Conexões e compartilhar sua conexão,
* como alternativa ao Filtro de Conexões
*
* @autor Marcelo Junior
*
* @data 27/12/2012
*/
public class ConnectionSingletonFactory {
private Connection connection;
// Usa o Padrão de Projeto Singleton
private ConnectionSingletonFactory() {
};
private static ConnectionSingletonFactory instance = new ConnectionSingletonFactory();
public static synchronized ConnectionSingletonFactory getInstance() {
return instance;
}
// Usa o Padrão de Projeto Factory Method
public Connection getConnection() {
if (connection == null) {
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/fj21", "usuario", "senha");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return connection;
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
// garante o fechamento da conexão
connection.close();
// deixa o objeto(conexão) anterior disponível para o coletor de lixo
connection = null;
super.finalize();
}
}
Exemplo em DAO
package br.com.caelum.jdbc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import br.com.caelum.jdbc.ConnectionSingletonFactory;
import br.com.caelum.jdbc.modelo.Contato;
/**
* @função Exemplo de utilização da ConnectionSingletonFactory
*
* @autor Caelum fj21
*
* @data 27/12/2012
*/
public class ContatoDAO {
private Connection connection = ConnectionSingletonFactory.getInstance()
.getConnection();
public void adiciona(Contato contato) {
String sql = "INSERT INTO contatos (nome,email,endereco,dataNascimento) VALUES (?,?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, contato.getNome());
stmt.setString(2, contato.getEmail());
stmt.setString(3, contato.getEndereco());
stmt.setDate(4, new java.sql.Date(contato.getDataNascimento()
.getTimeInMillis()));
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public List<Contato> getLista() {
try {
List<Contato> contatos = new ArrayList<Contato>();
PreparedStatement stmt = connection
.prepareStatement("SELECT * FROM contatos");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Contato contato = new Contato();
contato.setId(rs.getLong("id"));
contato.setNome(rs.getString("nome"));
contato.setEmail(rs.getString("email"));
contato.setEndereco(rs.getString("endereco"));
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("dataNascimento"));
contato.setDataNascimento(data);
contatos.add(contato);
}
rs.close();
stmt.close();
return contatos;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void altera(Contato contato) {
String sql = "UPDATE contatos SET nome=?, email=?, endereco=?, dataNascimento=? WHERE id=?";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, contato.getNome());
stmt.setString(2, contato.getEmail());
stmt.setString(3, contato.getEndereco());
stmt.setDate(4, new java.sql.Date(contato.getDataNascimento()
.getTimeInMillis()));
stmt.setLong(5, contato.getId());
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void remove(Contato contato) {
try {
PreparedStatement stmt = connection
.prepareStatement("DELETE FROM contatos WHERE id=?");
stmt.setLong(1, contato.getId());
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}