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?
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;
}
}
In my opinion first one is better as it looks more aligned to Object oriented approach.
While there's nothing particularly wrong with either solution, this solution from Wikipedia should give you the best compatibility and give you a thread-safe singleton:
University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[11] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Related
I want to know if code, containing a "master-class"(A class that should have only one instance) is considered implementing the "Singleton" design pattern or if there is another design pattern that follows this concept.
I created a class "GUI" and a class "MasterControl"
The class "MasterControl" defines alot of methods that interact with the GUI and contains a single "GUI" Instance on which it operates.
Code to demonstrate the basic idea.
public static void main(String[] args){
MasterControl controller = new MasterControl();
}
public class MasterControl{
private GUI Servant;
public MasterControl(){
Servant = new GUI(this);
}
}
public MasterControl(){
Servant = new GUI(this);
}
public class GUI{
GUIComponent c;
MasterControl master;
public GUI(MasterControl master){
this.master = master;
c = new GUIComponent(master);
}
}
//And so on
A Singleton design pattern means that it is impossible to create more than one instance of that class. Code that contains a "master class" is usually a class that represents the starting point of the code, it is proper format to initialize it once, but there is technically nothing stopping us from creating another instance of it. The presence of a master class does not necessarily make it a Singleton design pattern.
The classic implementation of a Singleton design pattern involves a private constructor with its own 'getter' method, as well as a static & uninitialized instance variable which will represent the single instance of the Singleton class. This design makes the constructor only available through the getter method, and can therefore be programmed to only be called when the getter method is called the first time. This would initialize the instance variable, which would then be returned from here on out. It would look something like this:
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
return instance;
}
}
I know of 2 ways to implement the singleton pattern in java and im wondering which one is better and why.
the first way is:
declare the constructor of the class private
have everything inside the class static - basiclly have the class instance itself be the singleton
second way is:
declare the constructor of the class private
have a static member to hold the singleton (which may be an instance of the class)
have a static getInstance() method
I tend to think that even though the second approach is the most common, the first approach may produce better code readability, both approaches seem similiarly efficient in runtime complexity, so i dont really get the reasons behind why the second approach is way more common and considered better practice...
enlighten me!
The first approach is not a singleton. A singleton is a class of which precisely one instance, no more, no less, can exist. The first thing is sometimes called a "static class", a "utility class," or an "uninstantiable class."
There are a number of things that you can do with a "real" singleton that you can't do with a utility class. For example, you can have a singleton that implements an interface or extends another class; you can't do that with the all-static-methods thing. The all-static-methods class is generally evidence that no object oriented design analysis was done
As far as how many ways there are to implement the singleton pattern in Java, there are actually quite a number of interesting ways, using different language features to defer initialization until absolutely needed: class loading, enumerations, or just a synchronized block and an if.
Testability of other classes that use the singleton is hampered by static methods. With an instance you can substitute a mock object or other forms of test double.
Advantages to the object-based singleton
Will your "singleton" ever, under any possibly non-imaginable circumstances, become a non-singleton?
Perhaps you'll want per-thread, per-connection, or some other categorization?
Door #2 leaves you with a future, without having to rewrite code.
You may have a singleton, but do you have only one implementation of that singleton? A common pattern is to have a factory method look at the runtime environment and make a determination as to which implementation of the "service" being offered by the singleton is appropriate. The commons-logging LogFactory is example of this type of singleton.
If I get your question, right.
Why is this #2
public class MySingleton {
static private MySingleton instance=new MySingleton();
private MySingleton() {}
static public MySingleton getInstance() { return instance; }
}
better than #1
...Sorry I don't get the first point...
-> Actually reading from other comments I got it. I confirm, having static methods doesn't mean you have a singleton. So the comparison is not even fair ;-/
Whatever it is, the reason why #2 is better is because of multi-threading.When the singleton is initialized from a static initializer, the jvm makes sure only one thread instantiates the class.
Well there are few interesting ways to implement singleton pattern. Let me recollect few of those implementations which i have read about:
The second approach you have mentioned in your question. (Not thread safe)
When you developing multithreaded applications you may have to use a lock (simple thread safety)
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Double check locking
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Not lazy, but thread-safe without using locks
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Fully Lazy Initialization
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
The third approach wont work in java.Becos Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance.
Hope this helps you.
Perhaps consider implementing a singleton using an enum:
public enum Singleton {
INSTANCE;
public void doStuff() {
System.out.println("Whoopee");
}
}
and call it like Singleton.INSTANCE.doStuff()
This is recommended in the book Effective Java by Josh Bloch
If you have a Java Singleton that looks like this:
public class MySingleton {
private static MySingleton instance;
private int member;
public static MySingleton getInstance(){
if(instance==null){
instance = new MySingleton();
}
return instance;
}
private MySingleton(){
//empty private constructor
}
public int getMemberA(){
return member;
}
public int getMemberB(){
return instance.member;
}
}
...is there a difference between getMemberA and getMemberB? That is, is there a difference between accessing the member with instance.xxx and just xxx?
Note: I am aware of the pros and cons of using the Singleton pattern!
Yes, there's a difference.
Your singleton implementation isn't currently threadsafe, which means it's possible to call getMemberB() on an instance other than the one referred to by instance, at which point you'll get a different result.
If your implementation were thread-safe (so genuinely only one instance could ever be created) then they'd be equivalent, and the simpler form would be much preferred.
No functional difference, but I find getMemberA() easier on the eye.
Note that your singleton isn't thread-safe. Two threads calling getInstance() concurrently could result in the creation of two objects. If this happens, the singleton contract is broken, and all bets are off.
No difference in behavior, however, I'd rather use 'return member' or even 'return this.member' as this looks more intuitively.
Thread-safety is a completely different topic and this simple singleton does not meet any thread-safe singleton requirements.
Your implementation of Singleton pattern uses lazy load technique. But it is not thread safe. We can use the synchronized keyword to make getInstance() method thread safe, but it hurts performance. It's better that we make double-check on private singleton member.
public class MySingleton {
private volatile static MySingleton instance;
public static MySingleton getInstance(){
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton();
}
}
}
return instance;
}
private MySingleton(){
//empty private constructor
}
}
Basically I have a class which an instance of is created via a Singleton class. The class should never been instantiated via any other means than the singleton class. My question is can the class be effectively 'not seen' by other classes, apart from Singleton.
I know inner classes and different pacakages etc would help, but I'm curious to see if anyone has a nice solution to this.
Thanks for replies
Just refactor class itself as singleton. Private constructor and etc.
An easy and efficient way to do Singleton with an Enum:
public enum Singleton {
INSTANCE;
public void execute (String arg) {
//... perform operation here ...
}
}
In a sample scenario, using your API, do I need to declare?:
ToBeInvisibleClass instance = TheSingleton.getThatInvisibleInstnace();
If the answer is Yes, then the answer to your question is No since I need to declare a variable and for that I need the type to visible. If the answer is No, then using inner/nested class seems to be a proper approach or making the class itself the singleton.
Java has no "friend" concept like C++
You mentioned nested classes (real inner classes will not work because they need the outer) and packages.
Other approaches to protected other classes but one from creating an instance are not known to me.
But in general there is no reason to build a singleton by an helper class.
You could build singleton using enums or static final vars
What is the best approach for using an Enum as a singleton in Java?
public enum Elvis implements HasAge {
INSTANCE;
private int age;
#Override
public int getAge() {
return age;
}
}
class X {
public static final X instance = new X ();
private X () {
}
...
}
To assure that instantiation only occurs through your class method, you can do the following:
Make the default constructor private
Save your singleton instance in a private method
Use a public static method to provide the instance to the clients:
In this site there's a nice example:
public class MySingleton {
private static MySingleton _instance = new MySingleton();
private MySingleton() {
// construct object . . .
}
public static MySingleton getInstance() {
return _instance;
}
By design, in Singleton pattern the constructor should be marked private and provide a creational method retuning the private static member of the same type instance. I have created my singleton classes like this only.
public class SingletonPattern {// singleton class
private static SingletonPattern pattern = new SingletonPattern();
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
return pattern;
}
}
Now, I have got to extend a singleton class to add new behaviors. But the private constructor is not letting be define the child class. I was thinking to change the default constructor to protected constructor for the singleton base class.
What can be problems, if I define my constructors to be protected?
Looking for expert views....
If you extend a singleton class via inheritance, you'll have 2 instances of the singleton class running around should someone grab your singleton and the original singleton.
If the original singleton is conceptually really supposed to be a singleton, then using composition is probably the way to go. However, then substitutability is lost (your class is not substitutable for the original singleton; it just uses it).
Do you have a concrete example?
If you do that, it's not a singleton. But perhaps you don't really need a singleton.
This is not the Singleton Class. Imagine I can call getInstance() static method n number of times and I can have n objects of this class thus completely violating Singleton Pattern. To make it Singleton you should check whether object is already created or not in getInstance() method. If already created then you should ignore and do not create again. For example, you can so something similar, please ignore syntax mistakes, just a code to explain, can vary in different languages.
public class SingletonPattern {// singleton class
private static SingletonPattern pattern = new SingletonPattern();
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
if(SingletonPattern == null) {
return new SingletonPattern();
}
}
Old question I know but happened to stumble upon this and think I can add something useful.
It is possible to have a protected constructor in a singleton class. If you want to have polymorphic behavior on your Singleton you can make it an abstract class, set the constructor to protected and delegate creation of the instance to one of the concrete sub classes.
I found the following example in the book "Design Patterns explained":
abstract public class Tax{
static private Tax instance;
protected Tax() {};
abstract double calcTax( double qty, double price);
public static Tax getInstance() {
// code to determine what implementing class to use
instance = USTax.getInstance();
return instance;
}
}
public class USTax extends Tax {
private static USTax instance;
private USTax() {
// instantation local members + Tax abstract class
}
public double calcTax ( double qty, double price){
// implementation
}
public static Tax getInstance() {
if(instance == null)
instance = new USTax();
return instance;
}
}