What could be a good use case for Immutable Singleton classes?

时间:2015-05-24 21:14:45

标签: java design-patterns singleton immutability

Without going into a discussion whether Singleton is an anti-pattern in itself, I'm looking for a good use case for Immutable Singleton.

The only instance of such class will have a constant value once initialized, since we can neither change its visible state nor create an another copy.

What is a real-life use of such constructs?

P.S.

Other than Enum please.

1 个答案:

答案 0 :(得分:2)

Maybe this could be an example of an immutable singleton:

public class DatabaseAccess
{
    private static DatabaseAccess instance;

    private final String dbUrl;
    private final String dbDriver;
    private final String username;
    private final String password;

    private DatabaseAccess()
    {
        Properties properties = new Properties();

        try { properties.load(new FileInputStream("db.properties")); }
        catch (IOException e)
        {
            // exception handling
        }

        dbUrl = properties.getProperty("dbmanager.url");
        dbDriver = properties.getProperty("dbmanager.driver");
        username = properties.getProperty("user.login");
        password = properties.getProperty("user.password");
    }

    public static DatabaseAccess getInstance()
    {
        if (instance == null)
            instance = new DatabaseAccess();

        return instance;
    }

    public Connection getNewConnection() { ... }

    // other methods ...

}

You want to read the properties once and only once for each JVM restart.