连接类,我应该使用Singleton吗?

时间:2017-01-26 20:06:26

标签: java singleton

我有一个名为SQLConnection的类,负责打开和关闭jdbc连接。有时候我需要打开一个连接,我需要读取一个xml文件来为类属性收费,然后我打开连接。

我在考虑为这个类创建一个单例设计模式,并在contructor的类上读取xml文件。

我问:哪种方法更好,哪种方式提供最佳性能?对类有静态intance,或者每次都读取xml并创建对象类?啊,这是一个拥有10~100个用户的Web应用程序。

这就像我在做:

public class SQLConnection {

    String url = ""; 
    String driver = "";
    String userName = "";
    String password = "";

    public Connection openConnection() {

        Connection conn = null;     
        this.setAtributes();        

        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        } 

        return conn;

    }


    public void closeConnection(Connection conn) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //read a xml file that have database infos
    public void setAtributes(){

        this.url = "lalala";
        this.userName = "lalala";
        this.password = "lalala";
        this.driver = "lalala";                 
    }
}

这就像我想做的那样:

public class SQLConnection {

    private static SQLConnection instance;

    String url = ""; 
    String driver = "";
    String userName = "";
    String password = "";

    private SQLConnection() {

    }

    public static synchronized SQLConnection getInstance() {
        if (instance == null)
            instance = new SQLConnection();
            setAtributes(instance);

        return instance;
    }

    public Connection openConnection() {

        Connection conn = null;     

        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        } 

        return conn;

    }

    //read a xml file that have database infos
    public static void setAtributes(SQLConnection instance){

        instance.url = "lalala";
        instance.userName = "lalala";
        instance.password = "lalala";
        instance.driver = "lalala";     
    }
}

1 个答案:

答案 0 :(得分:0)

简短回答:

单身人士解决资源争用问题。 对于SQL连接没有争用,您可以根据需要创建任意数量的连接。关于使用单身人士的更多细节如下: What is so bad about singletons?

正如其他人提到的那样,使用连接池会更好。您也可以通过连接池获得更好的性能。 关于连接池的好处:Why we need a connection pooling for JDBC?