Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Singleton Alternatively

The standard method of implementing singleton design pattern is this:

public class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }

    private Singleton() {}
}

I was wondering if you could also implement it like this:

public class Singleton {
    private Singleton() {}
    public final static Singleton INSTANCE = new Singleton();
}

and if yes which version is better?

like image 982
Mat.S Avatar asked Aug 13 '13 04:08

Mat.S


People also ask

What is an alternative to Singleton pattern?

Better Alternative of Singleton Pattern Instead, we will use dependency injection to inject a MockMailService, which doesn't send emails to the internal party. So, you can see that Dependency Injection offers a better alternative to Singleton Pattern in Java.

Why you should not use singletons?

By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.

Which of the following is an alternative for singleton in Java?

Using dependency injection to avoid singletons.


2 Answers

Neither. In both cases, a trusted consumer can invoke the private constructor via reflection. An additional problem is that it these implementation don't play nicely with serialization unless you take extra steps to make it so (by default, if you take the naïve approach, every time a Singleton is deserialized, it will create a new instance).

The correct solution is to use an enum that defines a single value.

public enum Singleton {
    INSTANCE;

    // methods
}

From Effective Java:

While this approach is yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

like image 121
jason Avatar answered Sep 29 '22 17:09

jason


Why you not use enum for realisation Singleton?

 public enum SingletonEnum {
     Instance;
     private static String testStr = "";

     public static void setTestStr(String newTestStr) {
         testStr = newTestStr;
     }

     public static String getTestStr() {
         return testStr;
     }

     public static String sayHello(String name) {
         return "Hello " + name;
     }
 }
like image 35
Rinat Mukhamedgaliev Avatar answered Sep 29 '22 17:09

Rinat Mukhamedgaliev