SINGLETON PATTERN IN JAVA?

Mikki Halpin

Total Post:23

Points:161
Posted by  Mikki Halpin
Java 
 789  View(s)
Ratings:
Rate this:
What is an efficient way to implement a singleton pattern in Java?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Singleton pattern in Java?

    Use an enum:

    public enum Foo {
        INSTANCE;
    }
    public enum Elvis {
        INSTANCE;
        private final String[] favoriteSongs =
            { "Hound Dog", "Heartbreak Hotel" };
        public void printFavorites() {
            System.out.println(Arrays.toString(favoriteSongs));
        }
    }

    "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!