我这几天看了一个采用JavaBean+JSP设计的网站,其中数据库连接的JavaBean为DBConnection.java,还有一个用来进行记录运行日志的类:Debug.java,这两个类都采用了单例模式,但是方式有不同,请教一下为什么要这样做呢?
DBConnection.java如下:
import java.sql.*;
/** * 本类用于与数据库建立接 */ public abstract class DBConnection{ private static Connection conn=null;
/** * 与数据库建立连接 * * 返回值-Connection对象 */ public static Connection getConnection(){ try{ if(conn == null){ Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital","root",""); Debug.log("Connection created."); }
else{ Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery("SELECT COUNT(*) FROM administrator"); if(rs==null||!rs.next()){ Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital","root",""); Debug.log("Connection re-created."); }
} } catch(Exception ex){ Debug.log(Debug.getExceptionMsg(ex)); } finally{ return conn; } } }
|
DeBug.java 如下: import java.io.*; import java.util.Date; import java.text.SimpleDateFormat;
/** * 本类用于将网站运行时遇到的异常信息记录到文件中 */ public final class Debug{ private static Debug instance=null; private static SimpleDateFormat dateFormat=null; private static FileOutputStream fos=null;
private Debug(){ }
/** * 初始化Debug对象 * * 参数: * path-日志文件存储路径 * * 返回值-Debug单例对象 */ static synchronized Debug init(String path){ String file=""; String fullPath="";
if(instance == null){ instance=new Debug(); dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); file="" + (new SimpleDateFormat("yyyy-MM-dd")) .format(new Date()) + ".log";
try{ fullPath=path + "\\" + file; fos=new FileOutputStream(fullPath,true); } catch(IOException ioe){ System.err.println("Cannot open file " + file + "," + fullPath); } }
return instance; }
/** * 将信息记入日志文件 * * 参数: * msg-信息 */ public static synchronized void log(String msg){ String s2=dateFormat.format(new Date()) + " " + msg + "\n"; if(instance != null) instance.writeFile(s2); else System.err.println(s2); }
/** * 将信息记入日志文件,供log(String msg)调用 */ private String writeFile(String msg){ if(fos == null){ return "Log file cannot be opened"; } try{ fos.write(msg.getBytes()); fos.flush(); } catch(IOException ex){ return ex.getMessage(); } return null; }
/** * 生成格式化异常信息 * * 参数: * e-异常 * * 返回值-格式化后的异常信息 */ public static String getExceptionMsg(Exception e){ StackTraceElement ste=e.getStackTrace()[0]; String msg=ste.getClassName() + "." + ste.getMethodName() + "() Ln " + ste.getLineNumber() + ": " + e.getMessage();
return msg; } }
|
DBConnection使用了abstract防止被实例化,而Debug使用final,并且设定私有构造函数,二者各自实现单例模式,但为什么要用这两种不同方式呢??请教各位!!!