【问题标题】:Connection class, should I use Singleton?连接类,我应该使用单例吗?
【发布时间】:2017-06-12 10:18:25
【问题描述】:

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

我想为这个类创建一个单例设计模式,并读取构造函数类的 xml 文件。

我问:哪种方法更好,哪种方法性能最好?对类有静态实例,还是每次都读取 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";     
    }
}

【问题讨论】:

  • 改用真实的连接池。
  • 永远不要使用单例进行连接。使用连接池。
  • 本可以停在第一句话,真的。不要使用单例,句号,直到你能清楚地说明为什么它是最好的方法。 (而且几乎从来没有。)

标签: java singleton


【解决方案1】:

简短回答:否。

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

正如其他人所说,最好使用连接池。您也将通过连接池获得更好的性能。 关于连接池的好处:Why we need a connection pooling for JDBC?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 2011-09-24
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多