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?
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.
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.
Using dependency injection to avoid singletons.
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.
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;
}
}
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