mercredi 15 juillet 2015

Static block vs singleton pattern

I want to learn what are the difference between using static block and singleton pattern.

enum Singleton
{
    INSTANCE;

    // instance vars, constructor
    private final Connection connection;

    Singleton()
    {
        // Initialize the connection
        connection = DB.getConnection();
    }

    // Static getter
    public static Singleton getInstance()
    {
        return INSTANCE;
    }

    public Connection getConnection()
    {
        return connection;
    }
}

Above is an example of singleton pattern while static block's example is following:

public class OneWithStatic {
    public static DBLoader dbl;
    static {
        dbl = new DBLoader();
    }

    ...
    Use dbl here

}

I want to understand which approach is better, not in terms of OOP. I know that singleton would be better from OOPs perspective. But I want to know if there is any other major difference between the two approaches.

Aucun commentaire:

Enregistrer un commentaire