Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring instance keyword in java

Tags:

java

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;
    } 
} 
like image 540
user1050619 Avatar asked Dec 29 '13 15:12

user1050619


1 Answers

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.

like image 65
GeertPt Avatar answered Sep 21 '22 12:09

GeertPt