I see a "instance" keyword being declared in my java code declaration of a ENUM.Can someone explain how this keyword works?
Java code:-
public enum TodoDao {
    instance;
    private Map<String, Todo> contentProvider = new HashMap<String, Todo>();
    private TodoDao() {
        Todo todo = new Todo("1", "Learn REST");
        todo.setDescription("Read http://www.vogella.com/articles/REST/article.html");
        contentProvider.put("1", todo);
        todo = new Todo("2", "Do something");
        todo.setDescription("Read complete http://www.vogella.com");
        contentProvider.put("2", todo);
    }
    public Map<String, Todo> getModel(){
        return contentProvider;
    } 
} 
                It is the best way to implement the GoF singleton pattern, according to Joshua Bloch, see related question: What is an efficient way to implement a singleton pattern in Java?
According to the java style guide, it should be all caps, though, i.e. INSTANCE.
To use this, you can call the following from any part of the code:
Map<String, Todo> todos = TodoDao.INSTANCE.getModel();
And you can be certain that the initialization will happen only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With