Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
public class Item3 {

public static void main(String[] args) {

    Singleton s=Singleton.Single.INSTANCE.getInstance();
    Singleton s2=Singleton.Single.INSTANCE.getInstance();
    System.out.printf("%b",s==s2);
}
}


class Singleton {
    enum Single{
    INSTANCE;
    Singleton s=new Singleton();
    public Singleton getInstance(){
        if(s==null)
            return new Singleton();
        else return s;
    }
    }
}
share|improve this question
add comment

3 Answers

up vote 7 down vote accepted

No, it is simpler to code than that:

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;
    }
}

Then you use can use final Singleton s = Singleton.getInstance(). Note however that since this is an enum you can always access this via Singleton.INSTANCE.

And NEVER do that:

public Singleton getInstance(){
    if(s==null)
        return new Singleton();
    else return s;
}

this is not thread safe! What is more, the new Singleton() value is never assigned to s... (thanks @DaveJarvis for noticing this!)

share|improve this answer
 
thanks. if I need to obtain a Database connection using singleton in this fashion then I would write enum Singleton{ INSTANCE; Connection c=DB.getConnection(); } and use Connection con = Singleton.INSTANCE.c in client code? Please correct me if my understanding is not correct –  n1234 Jun 12 '13 at 10:30
 
See my edit. While you could make the connection available as you say, it is something I would not recommend personally. –  fge Jun 12 '13 at 10:37
 
thanks.. sorry not enough reputation to vote up :-) –  n1234 Jun 12 '13 at 10:44
 
No problem ;) Glad I could help! –  fge Jun 12 '13 at 10:46
add comment

Your response and other samples in Singleton_pattern

public enum Singleton {
        INSTANCE;
        public void execute (String arg) {
                //... perform operation here ...
        }
}
share|improve this answer
add comment
public enum Singleton{
   INSTANCE;
}

This is enough; you can directly use Singleton.INSTANCE to get the instance of the class.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.