Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to duplicate/extend a static class's functionality?

The application I'm working on has a single class that maintains a database connection. All members of this class are static to enforce a singleton-like pattern, so the actual connection logic is performed in a static initializer block:

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    static void openSession() {
        //open session with sessionFactory
    }

    public static Session currentSession() {
        //return the currently open session
    }

    static void closeSession() {
        //close the currently open session
    }

}

However, the application now needs to open a database connection to a second database. The way this class in structured now, the only way to maintain the second connection while keeping the above pattern would be to create a second class (something like SecondHibernateUtil) and change the one line of configuration in the initializer block. That feels like a truly wasteful amount of copy/paste.

Can anyone suggest a way that I could rework this setup to maintain multiple connections simultaneously while not being overly destructive to the code already calling the existing methods?

like image 292
abeger Avatar asked Feb 17 '09 20:02

abeger


2 Answers

Keep the static methods and let them delegate to corresponding instance methods of a default instance.

For the secondary databases allow to create more instances by whatever means and access them via their instance methods.

Then you can chip away at the callers of the static methods, and when they are all gone remove the static methods.

like image 102
starblue Avatar answered Oct 03 '22 23:10

starblue


Maybe it shouldn't have been static in the first place.

like image 36
mmx Avatar answered Oct 03 '22 23:10

mmx