設(shè)計(jì)模式看懂了,好像是沒什么用的。只有在你的開發(fā)中運(yùn)用起來才有它的意義。
雖然還是小菜鳥,但既然看過了設(shè)計(jì)模式,還是希望能用起來的。
想做個(gè)自娛自樂的j2ee的東西。
關(guān)于得到數(shù)據(jù)庫連接部分,一開始覺得是用工廠模式,用工廠模式得到Connection對(duì)象,試了幾次好像不行。
然后嘗試單態(tài)模式,創(chuàng)造了一個(gè)DatabaseGeneralServices類,來提供數(shù)據(jù)庫連接和關(guān)閉數(shù)據(jù)庫等一些通用的服務(wù)。
一切正常。有點(diǎn)小感悟,代碼如下,希望高手指點(diǎn)。
package com.ClockWise.ray.persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DatabaseGeneralServices {
private DataSource ds;
private InitialContext ic;
private static DatabaseGeneralServices dgs = new DatabaseGeneralServices();
private DatabaseGeneralServices()//use singleton pattern, so the constructor is private
{
try{
ic = new InitialContext ();
ds = (DataSource)ic.lookup("java:jdbc/readshare");//get database connection
}catch(NamingException e){
e.printStackTrace();
}
}
public Connection getConnection(){
try{
return ds.getConnection();
}catch(SQLException e){
e.printStackTrace();
}
return null;
}
public void closeConnection(ResultSet rs,PreparedStatement ps,Connection conn){
try{
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
}catch(SQLException e ){
e.printStackTrace();
}
}
public static DatabaseGeneralServices getInstance()//get the sigleton instance
{
if(null==dgs){dgs= new DatabaseGeneralServices();}
return dgs;
}
}