当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: